Counter Factories
What you'll learn: How to create factory functions that produce independent counters, each maintaining its own private state through closures.
A counter factory is a function that returns a new counter object (or function) every time you call it. Each counter manages its own private count variable that no outside code can directly access or manipulate—only the returned functions can interact with that state.
The Basic Pattern
function createCounter() {
let count = 0; // Private state, captured by closure
return {
increment() {
count++;
return count;
},
decrement() {
count--;
return count;
},
getCount() {
return count;
}
};
}
const counterA = createCounter();
const counterB = createCounter();
counterA.increment(); // 1
counterA.increment(); // 2
counterB.increment(); // 1 (independent!)
console.log(counterA.getCount()); // 2
console.log(counterB.getCount()); // 1
Each call to createCounter() creates a new lexical environment with its own count variable. The returned methods form closures over that specific count, keeping it alive and private.
Why This Matters
Without closures, you'd need global variables or visible properties that anyone could accidentally modify. Counter factories give you:
- Encapsulation:
countis truly private - Independence: Each counter is isolated
- Reusability: Call the factory anytime to get a fresh counter
Think of it like a factory producing separate stopwatches—each has its own internal mechanism, and they don't interfere with each other.
Key Takeaway: Counter factories demonstrate closure's power to create multiple independent instances with private state, all from a single factory function.