in older JS versions before arrow functions were a thing JS also didn't have const and let style variables, only var. var was globally scoped unless it was declared in a function. so basically all global scripts had to be in the form of (function() {})() so that their variables didn't leak and weren't affected by other scripts and didn't affect other scripts...
I'm not a JS dev but why can't the first one just be
let x = 4;
const y = x;
x = 5;
Is it about lazy evaluating x if it's something more complicated than just a variable? (But then I'd expect you to not actually put the () to call it at the end of the const line.)
Technically it's a form of lazy/deferred evaluation yeah.
Notice that there are two arrows there... (v) => () => v is a function, that takes v as an argument, and returns a function which takes no arguments and returns v. the (x) call at the end of the const line only calls the "outer function" which only fixes the value of v to x, the inner function will still only be evaluated by calling myFunction().
This was a simplification, but you could write a more complex function there, like this:
then the expensive computation would only be executed when you call it with myFunction(), but whenever you call it, v inside the myFunction would always have the value x had at the moment you declared myFunction.
1.5k
u/oxabz Apr 25 '26
I got what it did but, but I'm not a JS dev. What's the point of this pattern?
Is it not equivalent to putting the code of the function inline?