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.
Reveal the answer and execution trace
1 2 1Each call to counter creates a new count binding. a and b retain independent state.
- Line 5. The first counter call creates the count used by a.
- Line 6. The second call creates a different count for b.
- 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.