whatstheoutput_

#70: let in a setTimeout loop

Topic: closures · Difficulty: ★★

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));
}

Output

0
1
2

Why

Unlike var, a for-loop's let binding is scoped to the LOOP, and the spec creates a fresh, independent copy of i for every single iteration (the new copy is even initialized by copying the previous iteration's value before the increment runs). So each arrow function closes over its own private i rather than one shared variable. The loop finishes synchronously, then the three queued timeouts run, each reading its own snapshot: 0, then 1, then 2. This is the direct fix for the classic var version of this bug, where every callback would print the same final value.

More closures puzzles

Play today's puzzle →