← JavaScript

Patterns & principles · 2 of 10 · 15 min read

The Factory pattern

A function that returns an object, why that beats a constructor more often than people expect, and where the memory cost shows up.

  • Design patterns

A factory is a function that returns a new object. That is the entire definition — no new, no class, no interface. What makes it a pattern is that the caller asks for a thing and does not have to know which concrete thing it gets.

The shape

function createUser(name, role = 'member') {
  return {
    name,
    role,
    describe() {
      return `${this.name} (${this.role})`;
    },
  };
}

const ana = createUser('Ana');
const beto = createUser('Beto', 'admin');

console.log(ana.describe());  // "Ana (member)"
console.log(beto.describe()); // "Beto (admin)"
console.log(ana === beto);    // false — a new object every call

A function that mutates an argument, or returns the same object each time, is not a factory:

const shared = { n: 0 };
const notAFactory = () => shared;              // always the same object
const alsoNot = (obj) => { obj.touched = true; }; // returns undefined

console.log(notAFactory() === notAFactory());  // true

Factory versus new

// Factory
function createPoint(x, y) {
  return { x, y, length: () => Math.hypot(x, y) };
}

// Constructor
class Point {
  constructor(x, y) { this.x = x; this.y = y; }
  length() { return Math.hypot(this.x, this.y); }
}

console.log(createPoint(3, 4).length()); // 5
console.log(new Point(3, 4).length());   // 5
Factory class / new
Caller must remember new no yes — it throws without it
this pitfalls none — there is no this a detached method loses it
Methods one copy per object shared on the prototype
instanceof no yes
Private state a closure # fields
Can return a different type yes only by returning an object
Memory for 100k objects higher lower

The two that decide most real cases are the first and the third. No new means no TypeError: Cannot read properties of undefined from a forgotten keyword and no this to lose when a method is passed as a callback:

const point = createPoint(3, 4);
const detached = point.length;
console.log(detached()); // 5 — the closure captured x and y, not `this`

const classPoint = new Point(3, 4);
const alsoDetached = classPoint.length;
// alsoDetached();       // TypeError: this is undefined

And per-instance methods are the price:

const a = createPoint(1, 1);
const b = createPoint(2, 2);
console.log(a.length === b.length); // false — two function objects

const c = new Point(1, 1);
const d = new Point(2, 2);
console.log(c.length === d.length); // true — one, on the prototype

For a few hundred objects that difference is invisible. For a hundred thousand particles in a render loop it is not, and that is when a class is the right answer.

If you want both — a factory’s call signature and a prototype’s shared methods — build the object with Object.create:

const pointMethods = {
  length() { return Math.hypot(this.x, this.y); },
};

function createSharedPoint(x, y) {
  const point = Object.create(pointMethods); // methods are shared
  point.x = x;
  point.y = y;
  return point;
}

const p = createSharedPoint(3, 4);
console.log(p.length(), createSharedPoint(1, 1).length === p.length); // 5 true

Choosing the variant for the caller

This is where it earns the name “pattern”: the caller states what, not which.

function createNotifier(channel) {
  switch (channel) {
    case 'email':
      return { send: (to, text) => `email to ${to}: ${text}` };
    case 'sms':
      return { send: (to, text) => `sms to ${to}: ${text.slice(0, 160)}` };
    case 'push':
      return { send: (to, text) => `push to ${to}: ${text}` };
    default:
      throw new RangeError(`unknown channel: ${channel}`);
  }
}

const notify = createNotifier('sms');
console.log(notify.send('+54...', 'hello')); // the caller never named a class

Adding a channel is one new case; the calling code does not change. Note that the switch itself is a smell once it grows — at that point the Strategy pattern’s lookup object is the better home for it, and the factory just reads from it.

With private state

A factory whose product closes over variables is the Module pattern applied per instance, and it is the most common shape of real JavaScript code that avoids classes:

function createAccount(owner, initial = 0) {
  let balance = initial;              // private, one per account
  const history = [];

  return {
    owner,
    deposit(amount) {
      if (amount <= 0) throw new RangeError('amount must be positive');
      balance += amount;
      history.push({ type: 'deposit', amount });
      return balance;
    },
    get balance() { return balance; },          // read-only
    get history() { return [...history]; },     // a copy, not the array
  };
}

const acc = createAccount('Ana', 100);
acc.deposit(50);
console.log(acc.balance);              // 150
acc.history.push({ type: 'forged' });  // writes to the copy
console.log(acc.history.length);       // 1 — the real history is intact
// acc.balance = 1_000_000;            // no setter: silently ignored, or TypeError in strict mode

Composing instead of inheriting

A factory can mix abilities together, which inheritance cannot do without a hierarchy:

const canFly = (state) => ({ fly: () => `${state.name} flies` });
const canSwim = (state) => ({ swim: () => `${state.name} swims` });
const canEat = (state) => ({ eat: () => `${state.name} eats` });

function createDuck(name) {
  const state = { name };
  return { ...state, ...canEat(state), ...canFly(state), ...canSwim(state) };
}

function createPenguin(name) {
  const state = { name };
  return { ...state, ...canEat(state), ...canSwim(state) }; // no fly, no awkwardness
}

console.log(createDuck('Donald').fly());    // "Donald flies"
console.log(createPenguin('Pingu').fly);    // undefined — correctly absent

With class Penguin extends Bird the penguin inherits fly() and you are left overriding it to throw. Each ability here is an independent function, and the factory picks the set it wants.

Where you already use one

console.log(Array.from('ab'));            // a factory for arrays
console.log(Object.create(null));         // a factory for objects
console.log(Promise.resolve(1));          // a factory for promises
console.log(document?.createElement?.name); // "createElement" — the DOM's factory

Array.of, Object.fromEntries, Promise.all, new Map()’s iterable form — the standard library is full of them, which is a good sign the pattern is idiomatic rather than imported from elsewhere.

Common mistakes

Forgetting to return

Mistake. A factory body that builds the object and ends without return. Why it fails. The function returns undefined, and the error surfaces at the call site as “cannot read properties of undefined” — far from the cause. What to do instead. Return the object. An arrow with a concise body makes it impossible to forget: const make = (n) => ({ n }) — note the parentheses, without them the braces are a block.

const broken = (n) => { n };   // a block with a useless expression
const fixed = (n) => ({ n });  // an object literal
console.log(broken(1), fixed(1)); // undefined { n: 1 }

Sharing a mutable default between products

Mistake. function create(opts = DEFAULTS) { return { opts } } with a module-level object. Why it fails. Every product holds the same object, so one caller mutating its options changes everybody’s. What to do instead. Copy at the boundary: { ...DEFAULTS, ...opts }.

Reaching for a factory when you need a hundred thousand of them

Mistake. A closure-based factory for every node of a large graph or every particle in a loop. Why it fails. Each product carries its own copy of every method. What to do instead. A class, or Object.create with a shared methods object.

Check yourself

One question from the bank on what you just read. Answering here does not affect your quiz history.

What makes a function a **factory** function?

Practise Design patterns →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.