Why is it that this code prints numbers 0 through 9
actions = []
for (let i = 0; i < 10; ++i) {
actions.push(() => console.log(i))
}
for (const action of actions) {
action()
}
but this code prints the number 10 ten times.
actions = []
let i
for (i = 0; i < 10; ++i) {
actions.push(() => console.log(i))
}
for (const action of actions) {
action()
}
According to MDN for the initialization portion of the for statement:
An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.
I would have interpreted this to mean that the variable i
is declared and initialized once and is local to the for loop, persisting between iterations. But it acts as though it's being re-declared and initialized on every iteration as let i = previous_i++