Build a counter factory using a closure
Implement createCounter() that returns an object with two methods: inc() increments a private count and get() returns the current count. The count must start at 0 and be inaccessible from outside except through these methods. Two counters created separately must keep independent counts.
function createCounter() {
// your code here
}
Write the implementation.
Declare a local let count = 0 inside createCounter, then return an object whose inc and get methods close over that variable. The returned methods keep a live reference to count after the factory returns, so it stays private. Each call to the factory creates a fresh count, giving independent counters.
- ✗Putting
counton the returned object as a public field instead of a closed-over local - ✗Assuming all counters share one count because they share the factory function
- ✗Believing
vargives block scope — it is function-scoped, not block-scoped
- →Why does each call to
createCounterproduce an independentcount? - →How would you add a
reset()method that closes over the same variable?
Solution
Declare a local count and return an object whose methods close over it.
function createCounter() {
let count = 0;
return {
inc() { count++; },
get() { return count; },
};
}
How it works
count is a local variable of createCounter. The returned inc and get methods form a closure: they hold a live reference to count even after the factory has returned. From the outside there is no way to reach count directly — only through these two methods, so it stays private.
Each call to createCounter() creates a brand-new count in its own scope, so two counters are fully independent: incrementing one does not affect the other. </content>