DEV Community 👩‍💻👨‍💻

Discussion on: Use Closures for Memory Optimizations in JavaScript (a case study)

Collapse
 
pcockerell profile image
Peter Cockerell

I didn't say a global variable, but "a more global scope", e.g. a static class property or a module-level const in node. The problem with paring your example down to such a degree is that you haven't shown closures' real utility. I think at the very least the outer function should have taken a parameter, so you could show that the inner function is implicitly parametrized by the argument passed to the outer function (similar to the currying that others have mentioned).

Another way to achieve exactly the same effect would be to make multiply() a method of a class Multiply, which has a fixed instance variable "x" per your example, or having x initialized in the constructor in the more realistic example. Though admittedly this is less in the spirit of function-based Javascript and more in line with the later class-based syntactic sugar.

In any case, I still don't believe that an example of closures where the only captured variable is identical for all instances of the closure is a very useful one.