My question is really more about scope in JavaScript, rather then closures.
Let s take the following code:
var f = function () {
var n = 0;
return function () {
return n++;
};
}();
console.log(f());
console.log(f());
The above code outputs:
0
1
As you can see from the above code, f
(self-invoked) returns a function, creating a closure of n
.
So, it works with an anonymous function; thus, I then tried it with a named function:
var f2 = function () {
return n++;
};
var f = function () {
var n = 0;
return f2;
}();
console.log(f2()); // <= [n is not defined]
The above code doesn t work, with the error n is not defined
. I assume that this is a scoping issue; but I cannot figure why exactly;
Why is it that the scope is the same with an anonymous, inner function but does not work with a named, outer function?
Also, in the second example, am I creating a closure?