easycodingjavascript~8 min
Implement createCounter()
Objective: Use closures to hold private, per-instance state.
Build a counter factory. Each counter keeps its own count, and the count can only change through the returned methods.
- createCounter(initial = 0) returns { increment, decrement, reset, value }.
- increment/decrement change the count by 1 and return the new count.
- reset() returns the count to `initial`; value() reads it.
- Counters are independent, and the count is not readable as a property.
const c = createCounter(5); c.increment(); c.increment();
→ c.value() === 7
JavaScript
⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor
Output
> Nothing has run yet.
Interview follow-up questions
- How would this differ with a class and `#private` fields?
- Can anyone still reach `count`? What about with a debugger or a heap snapshot?
- What memory cost does each counter instance carry?