0

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++

Chris_F
  • 4,991
  • 5
  • 33
  • 63

1 Answers1

2

i is indeed local to the loop - it's declared and initialized in every iteration of the loop, and thus you get the values 0 through 9.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Upvoted as this is correct. – Unmitigated Dec 26 '22 at 21:41
  • The fact that MDN says that it's "typically used to initialize a counter variable" and " evaluated once before the loop begins" makes that very confusing. – Chris_F Dec 26 '22 at 21:46
  • I'll admit I'm not a huge fan of this phrasing. I find the best way of think about it is that the loop initialization is tacked on to the beginning of the loop body. – Mureinik Dec 26 '22 at 21:48