DEV Community šŸ‘©ā€šŸ’»šŸ‘Øā€šŸ’»

DEV Community šŸ‘©ā€šŸ’»šŸ‘Øā€šŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in

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

Collapse
 
pcockerell profile image
Peter Cockerell

I think examples, no matter how trivial, should show code that people would actually write. Why would anyone use pow() (or **) to create the constant 1e10? And why would anyone put such a constant in a function scope rather than a more global scope, where it would be evaluated exactly once in the lifetime of the program (instead of every time the outer function is called)?

I find these questions so distracting, they totally obscure the point the article was trying to make, and the example is essentially an anti-pattern for the usage of closures.

Collapse
 
ahmedgmurtaza profile image
Ahmed Murtaza Author • Edited on

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.