var x = arr[i];
var f = function() { console.log(x) };
In these two lines, console.log(x)
thinks that it just has to print x
. So, all the three functions are created that way only. So, when you immediately execute the functions, the value of x
is different in each of the iterations. But when the looping is over, the variable x
retains the last value it held and when the dynamically created functions are executed, they simply print the value of x
which is c
.
So, in order to fix this, you have to have your own copy of x
, for each dynamically created function. Normally, we retain the current state of the variable which changes in the loop, with a function parameter, like this
var f = function(x) { return function() { console.log(x) } }(x);
Now, we are creating a function and executing it immediately, which returns another function and that returned function actually prints the value of x
.
function(x) {
return function() {
console.log(x)
}
}(x);
We are passing the value of x
as a parameter to the wrapper function and now the current value of x
is retained.