Closures & scope · Output question
JavaScript closures in a let loop
Several functions close over a loop variable declared with let. Predict what they read when called after the loop.
const readers = [];
for (let round = 0; round < 3; round++) {
readers.push(() => round);
}
console.log(readers.map(read => read()).join(","));What gets logged?
Choose an output before opening the walkthrough, or check your answer in practice mode.
Reveal the answer and execution trace
0,1,2A let variable in a for loop gets a separate binding for each iteration. Each callback retains its own binding.
- Line 2. The first iteration creates a round binding with value 0.
- Line 3. The callback closes over that iteration’s binding.
- Line 2. The next two iterations have their own bindings with values 1 and 2.
- Line 5. Reading each retained binding produces 0, 1, and 2.
Reference: Closures in loops on MDN.