DEV Community

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

Collapse
 
ahmedgmurtaza profile image
Ahmed Murtaza • Edited

Hi @pcockerell , I value your anguments, however keeping global values itself is an anti pattern. Second, using high exponential expressions was only meant to show jobs which could affect smooth performance. Although these patterns might not benefit in smaller code bases but would surely payoff in much larger applications.

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.