codecks.

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.

  1. 0,1,2
  2. 3,3,3
  3. 2,2,2
  4. ReferenceError
Reveal the answer and execution trace
0,1,2

A let variable in a for loop gets a separate binding for each iteration. Each callback retains its own binding.

  1. Line 2. The first iteration creates a round binding with value 0.
  2. Line 3. The callback closes over that iteration’s binding.
  3. Line 2. The next two iterations have their own bindings with values 1 and 2.
  4. Line 5. Reading each retained binding produces 0, 1, and 2.

Reference: Closures in loops on MDN.