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
You cannot access any variables defined within the enclosure outside that enclosure. That helps you avoid conflicts, like if the same variable name is used by several functions.