0

The way I understood closures was that the local variables will have the updated values. So, I expected all 3 method calls to print 3.

In this example somehow, the current value of i is stored in the array position along with the function object reference. But I don't understand what is happening. i is given in parenthesis, (i) at the end of the statement where function object is stored in the array.

Can someone please explain how the code works

function f() {
    var a = [];
    var i;
    for(i = 0; i < 3; i++) {
        a[i] = (function(x){
            return function(){
                console.log(x);
            }
        })(i);
    }
    return a;
}


var a = f();
a[0](); //0
a[1](); //1
a[2](); //2
Enzio
  • 799
  • 13
  • 32
  • `i` is just passed to a function, an IIFE, and enclosed in another scope as an argument passed in on execution, hence it keeps it's value – adeneo Jul 01 '17 at 13:06
  • `f` returns an array, but functions are stored in this array. These inner functions are called with `a[i]()`. To pass a parameter to the inner function you have to use the notation `(function(){...})(param)`. – Marco Luzzara Jul 01 '17 at 13:15
  • @MarcoLuzzara thank you for telling me about that notation. That was the part I didn't understand. I didn't encounter that syntax while studying. If possible can you please send me a link to documentation about it. – Enzio Jul 01 '17 at 13:26
  • It can't be properly called "notation": it's actually a way to capture the local variable `i`, otherwise if you only write `function(){//here you use i}`, `i` is not in the scope of the function anymore. To understand this better, I strongly suggest you to take a look at the MDN reference https://developer.mozilla.org/en/docs/Web/JavaScript/Closures – Marco Luzzara Jul 01 '17 at 14:44

0 Answers0