2

If I have the following code:

function foo() 
{
    var a = [];
    for(var i = 0; i < 3; i++)
    {
        a[i] = function(x)
        {
            return function()
            {
                return x;
            }
        }(i);
    }
    return a;
}

the closure is created when I call (i) at every iteration or when I define the inner functions?

and then a lambda expression is a closure?

Thanks.

xdevel2000
  • 20,780
  • 41
  • 129
  • 196

3 Answers3

1

the closure is created when your define the function, not when you run it -- this is called lexical scoping.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
1

The closure is created by virtue of the fact that you're returning a function that has access to the local variable x, which was defined as the only member of the formal parameters list.

So the functions stored at a[i] have closed around their unique x which was in the same scope, and as such, have access to it. Because this variable is accessible only by this function that was passed out of the self invoking function, you have a closure.

I'd note that it would be better if you did not use a self invoking anonymous function here since it is unnecessary and adds overhead. Instead declare a named function, and call that.

function foo() 
{
    var a = [];
    function retain_i(x)
    {
        return function()
        {
            return x;
        }
    }
    for(var i = 0; i < 3; i++)
    {
        a[i] = retain_i(i);
    }
    return a;
}

EDIT: To be more specific to your question:

the closure is created when I call (i) at every iteration...

No, this doesn't create a closure. The closure is created when you return the function that has closed around the x parameter, which would be otherwise inaccessible outside the self-invoking function.

If you didn't return that function, you wouldn't have a closure.

So as you can see from the modified code example I gave, the definition/declaration of a function doesn't create a closure. Rather the execution of a function that passes out of it some other function that has access to otherwise inaccessible variables creates a closure.

user113716
  • 318,772
  • 63
  • 451
  • 440
  • 1
    According to the environments model, the closure is created *when you define a function*. It does not matter if the closure outlives the surviving context or does not. – EFraim Dec 06 '10 at 22:22
0

Closures are created on function definitions.

Therefore in your example they are created twice for each iteration - first time when the outer function is declared, and a second time when it is invoke, defining an inner function.

The result assigned to the cell i of the array are functions returning i.

The other poster is correct in calling it "lexical" scoping - most modern languages seem to use it.

EFraim
  • 12,811
  • 4
  • 46
  • 62