codecks.

Closures & scope · Output question

JavaScript closures from separate factory calls

A counter factory creates local state for returned functions. Predict whether two counters share their count.

function counter() {
  let count = 0;
  return () => ++count;
}
const a = counter();
const b = counter();
console.log(a(), a(), b());

What gets logged?

Choose an output before opening the walkthrough, or check your answer in practice mode.

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

Each call to counter creates a new count binding. a and b retain independent state.

  1. Line 5. The first counter call creates the count used by a.
  2. Line 6. The second call creates a different count for b.
  3. Line 7. Arguments are evaluated left to right: a increments to 1, then 2, then b increments to 1.

Reference: Independent closure state on MDN.