codecks.

Closures & scope · Output question

JavaScript closures in a var loop

Functions created during a loop share a variable declared with var. Predict the values they read after iteration finishes.

const readers = [];
for (var 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. 2,2,2
  3. undefined,undefined,undefined
  4. 3,3,3
Reveal the answer and execution trace
3,3,3

All three callbacks read the same var binding. When the callbacks run after the loop, that binding holds 3.

  1. Line 2. var creates one round binding for this scope.
  2. Line 3. Each callback retains access to the same binding.
  3. Line 2. The final increment makes round equal 3 and the loop exits.
  4. Line 5. Every callback reads the value 3.

Reference: Shared closure bindings on MDN.