Reputation: 1355
What's the difference (in num++
) between:
function numberGenerator() {
// Local “free” variable that ends up within the closure
var num = 1;
function checkNumber() {
console.log(num);
}
num++;
return checkNumber;
}
var number = numberGenerator();
number(); // 2
number(); // 2
number(); // 2
and
function numberGenerator() {
// Local “free” variable that ends up within the closure
var num = 1;
function checkNumber() {
console.log(num);
num++;
}
return checkNumber;
}
var number = numberGenerator();
number(); // 1
number(); // 2
number(); // 3
Why doesn't the first code remember the value of num
?
Why is it 2 instead of 1?
Upvotes: 1
Views: 80
Reputation: 407
At the time of function invocation (var number = numberGenerator), the closure 'checkNumber()' has access to the local variable 'num', and holds onto that value even after it is incremented with num++. The closure has direct access to the local variable 'num', and changes it each time it is accessed using the variable 'number'. This only works when num++ is inside of the closure, as the closure has direct access to the local variables in the function that it is contained in. Douglas Cockford's book "JavaScript: the good parts" has helped me a lot in creating and understanding closures.
I hope this helps!
Upvotes: 1
Reputation: 5955
In fact it does remember it very well. num's variable-name-value is always 2, no matter how many time you persist in calling it; i.e.: the execution of the returned closure of the variable-name number.
It will forever remain 2.
That's because in the first function your closure
doesn't have a hold on num variable.
doesn't cause the num increase.
each call will be returning the result of the host function (num++)increase, which has happened only once. And its value is already 2.
All the same if you call numberGenerator, again because the num value will be re-declared / reset to 1 and than increased and self assigned a value 2 at its next declaration.
So, there is no difference, its just that the closure in your first, cannot increase the num variable value, since it doesn't have he means to do it.
Upvotes: 1
Reputation: 4946
Example 1 is initialized with var num = 1;
and then increased with num++;
. It doesn't matter how often you call the first function because the value of num
is never changed again, it will always be 2. Only the console.log(num);
is executed when you call number()
in Example 1.
In Example 2 num++;
is executed each time you invoke the function. Therefore it will increase with each call.
Upvotes: 1
Reputation: 32066
Because when you run number()
in the first example, num++
isn't executed again, because it's not in that function.
Upvotes: 3