whatstheoutput_

#72: Two counters from the same factory

Topic: closures · Difficulty: ★★

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

Output

1 2 1

Why

Each call to makeCounter() creates a brand new count variable and a brand new arrow function that closes over that specific variable — they do not share state just because they came from the same function body. a and b are two separate closures, each with its own private count living in its own call's memory. Calling a() twice increments a's count to 1 then 2; calling b() for the first time increments a completely separate count that starts fresh at 0, giving 1. That's the essence of a closure-based counter: state is private per invocation of the factory.

More closures puzzles

Play today's puzzle →