function makeCounter() {
let n = 0
return {
increment() { return ++n },
reset() { n = 0 },
value() { return n },
}
}
const counter = makeCounter()
counter.increment() // β 1
counter.reset()
counter.value() // β 0Returning an object of methods from a closure lets multiple operations share the same private variable, forming a clean stateful API.
Extend the counter concept by returning an object with multiple methods that share access to the same internal state.
Challenge: Create a makeCounter function that returns an object with three methods:
increment() - increments counter by 1 and returns the new valuereset() - resets counter to 0value() - returns current counter value without incrementingExample:
const counter = makeCounter()
counter.increment() // 1
counter.increment() // 2
counter.value() // 2
counter.reset()
counter.value() // 0