closure in javascript
so i am learning javascript and i came across a section that side we should generally try to avoid side effect but upon reaching the closure part it seems like every closure i have seen has side effect so my question is in what cases should we use closure ?
3 Replies
also please if anyone can explaint this to me i can't still wrap my head around it
Avoiding closures part is like many code things just partially true, comes down to the specific use cases but if the intention and effects are clear doesn't hurt to use if it helps the code be more concise
As for the snippet you've shared,
number => number * factor , is just a shorthand for
function (number) { return number * factor }
So essentially the multiplier function takes in a factor and returns a function with factor baked in as the multiplier
So when you do twice. = multiplier(2), twice is now (number) { return number * 2}
So twice(5) will give you 10Closures were the hardest part for me first starting out with js. It's really not that complicated, it's how almost every language you've ever used works. It's just a fancy work for generating a new function where some variables are known at one level, and then the second level (i.e.
twice(5)) gives the function the rest of the variables necessary.
In your example, multiplier sets up the factor variable, and then twice is responsible for giving the number variable.
There is a slight difference with how closures work between arrow functions, function() {}, and class methods, but realistically that's such an edge case where you'll probably know you're doing something funky when you get to it, there's not much need to stress about it beforehand.