Skip to content
jshacks.dev
Patterns

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.

1 min read
Summarize in AI

A factory function builds an object and keeps its state in variables that nothing outside can touch. There is no new and no this.

JavaScript
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);
Text
2 11

Each 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.

Taggednode 24
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.