Here is a piece of code :
// -------- Sample 1 ---------------
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs[i] = function() {
console.log("My value: " + i);
};
}
for (var j = 0; j < 3; j++) {
funcs[j]();
}
// --------- Sample 2 --------------
var fun = [];
for(var i = 0;i < 3; i++) {
fun[i] = function() {
console.log('values is '+ i);
}
}
for(var i = 0; i < 3; i++) {
fun[i]();
}
Both the sample codes are same except the variable names. But it's giving different output. The output of the above code is :
My value: 3
My value: 3
My value: 3
values is 0
values is 1
values is 2
Can any one figure out why its happening ? DEMO