Implement a factory function
Implement a factory function in JavaScript that returns objects with private state in a closure and no this or new. Node.js 24.
A factory function builds an object and keeps its state in variables that nothing outside can touch. There is no new and no this.
function createCounter(start = 0) {
let count = start;
return {
increment() {
return ++count;
},
get value() {
return count;
},
};
}
const a = createCounter();
const b = createCounter(10);
a.increment();
a.increment();
b.increment();
console.log(a.value, b.value);2 11Each call creates a fresh count, so the two counters are independent. The methods close over it, and the only way to change it is through them. A caller cannot write a.count = 99, because the property does not exist.
Compared with a class, the methods are created again for every object, which costs memory when you make thousands of them, and instanceof does not work. Choose a factory for a handful of objects with private state, and a class when you need many cheap instances or inheritance.