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
Aleed.dev
Aleed.devOP4mo ago
also please if anyone can explaint this to me
function multiplier(factor) {
return number => number * factor;
}

let twice = multiplier(2);
console.log(twice(5));
function multiplier(factor) {
return number => number * factor;
}

let twice = multiplier(2);
console.log(twice(5));
i can't still wrap my head around it
hari_07
hari_074mo ago
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
Nate
Nate3mo ago
Closures 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.

Did you find this page helpful?