2
votes

This is the code example of JS Closure concept.

 function buildFunctions() {
        var arr = [];
        for (var i = 0; i < 3; i++) {
            arr.push((function(j) {
                return function() {
                    console.log(j);
                }
            }(i)));
        }
        return arr;
    }
    var fn = buildFunctions();
    fn[0]();
    fn[1]();
    fn[2]();

In this code i know when the loops starts to run and for each 'i' value(for each IIFE) new execution context with variables j=1,2,3 will be created respectively in JS engine. So when the loops finishes, the three returned functions from the 3 IIFE will sit in the var arr and the execution context of respective IIFE's will be gone but still having their variable environment with j=1,2,3 in the closure. So, now the arr will have

  var arr = [function{console.log(j)},function{console.log(j)},function{console.log(j)}]

My question is how the invoking of these functions in the array, fn[0]() picks j=0, fn[1]() picks j=1, fn[2]() picks j=2 from the closure respectively.?

If something is wrong in my understanding please help me...

2
Each closure is a separate object, and has access to exactly the y variable that is in its scope. Notice there are multiple y variables (with the different values) in multiple scopes (that were created by each invocation of that IEFE).Bergi
@Bergi Can I just think each round of that push create a container( the closure) in the world that .push get called and put all local variables into it and pass a reference of that container to the function get pushed?Kuan
Yes, but the scope (of the IIFE) is the container and the function (with the reference) is what is called "closure".Bergi

2 Answers

3
votes

when the loops finishes […] the execution context of respective IIFE's will be gone

Well, they're not gone - that's the point of closures.
Each closure keeps the context it was created in alive - so each of your functions has a reference to their variable j from the respective scope, with the respective value.

1
votes

The function logs the value of j.

The value of j is the value passed as an argument to the outer anonymous function.

That is specified when that function is called (immediately) as the value of i.

i only has one value at a time.