views:

145

answers:

5

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?

+2  A: 

There is no way for f2 to figure out where it should take variable n.

In first example anonymous function is inside function f, in second - outside (f2 instead of anonymous). So, f2 cannot access variable n, because it is in another scope and inaccessible (invisible). Try put f2 declaration inside f.

Roman
+3  A: 

The closure is created in the first example because the code in the anonymous function uses a local variable that is declared outside of the anonymous function.

In the second example the scope of the n variable in the function f2 is already decided when the function is declared. Creating a local variable with the same name doesn't change the meaning of the function, and using the function inside another function doesn't change it's scope. Thus, the function doesn't use the local variable.

Guffa
A: 

In your second example, you are not creating a closure, you are simply returning a global variable. f2 is not being closed over because it was declared in a more general (in this case, global) scope, and n is declared in a more specific scope. Closure is possible down the scope chain "funnel," not up, and is only effective when all related entities are defined in the same scope.

Justin Johnson
A: 

We could rewrite your second example to make it work with a named function:

var f = function() {
    var n = 0;
    var f2 = function() {
        return n++;
    };
    return f2;
}();
console.log(f());
console.log(f());

This would output, 0 and 1 as your first example did.

As the other answers have stated, its not about the function being named or anonymous, its about scope of n and f2. Since you declared f2 outside of f in your example, it had no access to the variable n declared inside the scope of f.

Ben Delarre