M_V
M_V

Reputation: 105

Variable's value of JS Closure

Could you please try to explain me how does it work that variable i isn't re-initialized to zero value when function a is called for the second time. Thank you

var a = (function () {
    var i = 0;
    return function () {return i += 1;}
})();

a();
a();

Upvotes: 1

Views: 43

Answers (1)

Pointy
Pointy

Reputation: 413702

The value of a isn't the function in which i is declared in the var statement. Instead, a is the function that that function returns when it is called during the initialization of a. Thus, a is the function

function() { return i += 1; }

The i in that function refers to the i that was in the enclosing anonymous function. It is essentially a persistent value that the a function can reference (and modify) each time it is called.

Upvotes: 2

Related Questions