Reputation: 1557
I'm studying closures and found the following example code for incrementing a "private" variable named count:
function setup() {
var count = 0;
return function() {
count += 1;
console.log(count);
}
};
var next = setup();
next();
This makes sense to me. However, when I experimented with passing the variable as an argument to the nested function, next() logs 'NaN' to the console. Eg:
function setup() {
var count = 0;
return function(count) {
count += 1;
console.log(count);
}
};
var next = setup();
next();
Can someone explain why this happens?
Upvotes: 0
Views: 112
Reputation: 2511
It's because the inner function now has access to a more local variable, so it doesn't look at any closures it has access to for the "count" variable. And nothing is passed, so count is undefined.
This answer may be useful: Scope Chain in Javascript
Upvotes: 0
Reputation: 816422
Can someone explain why this happens?
Inside the closure, count
now refers to the parameter, function(count) {
. Since you are not passing any argument when you call the function, count
is undefined
and adding a number to undefined
results in NaN
.
when I experimented with passing the variable as an argument to the nested function
To be clear: The count
parameter has nothing to do with the count
variable defined in the outer function. You are not passing the variable as argument, because you are not calling the function, you are defining it.
Upvotes: 2