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 ?
2 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 10