Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 492
pedroyanky Avatar asked Mar 24 '26 09:03

pedroyanky


1 Answers

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.

like image 173
Moishe Lipsker Avatar answered Mar 26 '26 21:03

Moishe Lipsker