I'm new to javascript closures. My question is, in the SO post about javacript closures, the first code block
var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value.
console.log("My value: " + i);
};
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}
outputs
My value: 3
My value: 3
My value: 3
But how is it that when I re-use i
variable in the second for loop, there is no closure?
var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value.
console.log("My value: " + i);
};
}
for (var i = 0; i < 3; i++) {
// and now let's run each one to see
funcs[i]();
}
How is the output in the second code block
My value: 0
My value: 1
My value: 2