I'm trying to validate my JavaScript closure understating and i come to strange behavior which i can't understand.
Lets write the first loop:
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]();
}
this will output
My value: 3
My value: 3
My value: 3
which is what i expected. But now lets change the second loop a little bit:
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs[i] = function() {
console.log("My value: " + i);
};
}
for (var i = 0; i < 3; i++) { // i only changed the j var to i
funcs[i]();
}
the output will be:
My value: 0
My value: 1
My value: 2
Could someone explain me why i get different results in the second example?
Here is a example which i wrote in angularjs: http://plnkr.co/edit/CipIQe9x8QBX7AFg4xfI?p=preview