I was researching var vs. let and I stumbled upon a question containing this code
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]();
}
The output confused me, it was
My value: 3 My value: 3 My value: 3
instead of
My value: 0 My value: 1 My value: 2
The top answer for this question says
Well, the problem is that the variable
i
, within each of your anonymous functions, is bound to the same variable outside of the function.
Why is this? What is happening in the JavaScript engine that causes this?