In this classic interview question, a new i
is created for each iteration. This new i
has closure with the function in setTimeout
and produces the output 0 1 2 3 4
. I don't understand why a new i
is initialized when it's declared with let
but not when it's declared with var
. That should be impossible since let
doesn't allow another variable with the same name to be created. Also, since closures are created when a function is defined, shouldn't the anonymous function in setTimeout
still have closure around the original i
equal to 0 in the block scope? Thanks.
for (let i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
//Output:
//0
//1
//2
//3
//4