The Counter II interview question is an evolution of the basic counter problem. Instead of just incrementing, you need to return an object with three methods:
increment(): Increases the current value by 1 and returns it.decrement(): Decreases the current value by 1 and returns it.reset(): Sets the current value back to the initial starting value and returns it.Microsoft and Amazon use the Counter II coding problem to test a candidate's ability to create simple APIs using closures or classes. It evaluates how you organize related logic and manage state resets. It’s a classic example of "Encapsulation," where the internal count is hidden from the outside world and only accessible via the provided methods.
This problem uses the Object Factory / Closure pattern.
initialValue and a currentValue.currentValue and returns the result.const counter = createCounter(5);
counter.increment() -> returns 6.counter.reset() -> returns 5.counter.decrement() -> returns 4.
The reset() method specifically needs to remember the original init value passed to the factory function.reset() must return the original starting value, not necessarily zero.While this can be solved with a Class, using a closure is often preferred in modern JavaScript interviews as it demonstrates a better grasp of the language's functional roots and provides true private variables.