I'm learning JS. Why does logging funcs2[1]();
log 4 and funcs[1]();
logs 5?
Note that this is not a duplicate of this question. I know that funcs[1]();
logs 5
(and not 1) because the function called is bound to the current value of i
, which is 5 when the loop terminates.
But that's not my question. I want to know why funcs2[1]();
log 4 and not 5.
var funcs = [];
for (var i = 0; i < 5; i++) {
funcs.push(function () {
return i;
});
}
console.log(funcs[1]());
5
var funcs2 = [];
for (var i = 0; i < 5; i++) {
var x = i;
funcs2.push(function () {
return x;
});
}
console.log(funcs2[1]());
4