I'm trying to understand how scopes work in JS. Can you tell me if I correct with understanding of this chunk of code:
for(var i = 0; i<5; i++){
setTimeout(function timeoutHandler() {
var i = i;
console.log(i); //undefined
})
}
console.log
prints undefined
5 times. So as I understand, when timeoutHandler
is executed, it has its own local scope with own i
variable. So is that correct that during timeoutHandler
execution, the interpreter asks for i
variable, finds it declared in local scope and uses this declared variable for assignment? This explains why it is undefined
, but I'm not sure I'm fully correct.
Thanks
UPD I don't need this code to work properly, I just want to understand why it behaves like that in this case