I’m having a hard time discerning how exactly JavaScript closures work. Please take a look at these two functions and tell how they are different that they produce entirely different results when called multiple times:
var add = (function() {
var counter = 0;
return function() {
return counter += 1;
}
})();
console.log(add()); // result is 1
console.log(add()); // result is 2
console.log(add()); // result is 3
function add() {
var counter = 0;
function() {
return counter += 1;
}
plus();
}
console.log(add()); // result is 1
console.log(add()); // result is 1
console.log(add()); // result is 1
In the first example, counter is declared and the function being called when invoking add is essentially:
function (){
return counter += 1;
}
This is important because counter isn't being redeclared every time add is being called.
In the second example, counter is being redeclared each time add is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With