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