Search code examples
javascriptlexical-closures

How is this pair of JavaScript functions different?


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:

Function 1

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 2

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


Solution

  • 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.