Consider this classic JavaScript closure function. I understand how the closure is exhibited. I understand that the inner function closes in on the variable i, which is 3.
What I dont understand is why the array should contain the variable i, when all we are doing is pushing a function into an array where i has a value from the for loop.
function buildFunctions() {
var arr = [];
for (var i = 0; i < 3; i++) {
arr.push(function() {
console.log(i)
})
}
return arr;
}
var fs = buildFunctions(); // [function(){console.log(1)}, ...and so on]
//not [function(){console.log(i)} ...and so on]
fs[0](); // outputs 3
fs[1](); // 3
fs[2](); // 3
otherwise, this would return the correct(imo) contents of the array:
function buildFunctions() {
var arr = [];
for (var i = 0; i < 3; i++) {
arr.push(i)
}
return arr; // [0, 1, 2]
}