Okay. I know Javascript uses function scoping versus block scoping, but I cannot figure out why this example of this behavior works like it does.
var txt = ["a","b","c"];
for (var i = 0; i < 3; ++i ) {
var msg = txt[i];
setTimeout(function() { console.log(msg); }, i*1000);
}
//outputs c, c, c
It seems to me that if i
is being "hoisted" to the top of this code block then i
would equal 0, then 1000, then the for loop would break is because 1000 > 3. So why does this loop behave the way it does?
EDIT: I know this has something to do with msg = txt[i]
, because the code works like it seems it should when:
var txt = ["a","b","c"];
for (var i = 0; i < 3; ++i ) {
let msg = txt[i];
setTimeout(function() { console.log(msg); }, i*1000);
}