Skip to content
jshacks.dev
Patterns

The Factory Method Pattern in JavaScript, With Real Examples

The factory method pattern lets a function or subclass decide which object to create. See classic, functional and registry versions in JavaScript with output.

8 min read
Summarize in AI
Flat illustration of a factory producing database records, with the JavaScript, npm, Node.js and Vite logos.

The factory method pattern defines a way to create an object while letting the creator decide which concrete type to return. The caller asks for "a notifier" and receives an email notifier or an SMS notifier, without writing new EmailNotifier() itself. The benefit is that the code that uses the object does not depend on the concrete class, so adding a type does not change the callers. The Gang of Four book describes it with subclasses overriding a createProduct method, but in JavaScript the most useful forms are plain factory functions and lookup tables. This post shows the classic version, the functional version, a registry that makes extension a one-line change, async factories and where the pattern is overkill, on Node.js 24. Every sample prints its output.

The problem: new scattered everywhere

Look at code that constructs concrete types at each call site.

scattered.mjsJavaScript
class EmailNotifier {
  send(to, text) {
    return `email to ${to}: ${text}`;
  }
}
class SmsNotifier {
  send(to, text) {
    return `sms to ${to}: ${text}`;
  }
}

function notify(user, text) {
  const notifier = user.prefersSms ? new SmsNotifier() : new EmailNotifier();
  return notifier.send(user.contact, text);
}

console.log(notify({ prefersSms: true, contact: "+15550100" }, "Your order shipped"));
console.log(notify({ prefersSms: false, contact: "[email protected]" }, "Your order shipped"));
Text
sms to +15550100: Your order shipped
email to [email protected]: Your order shipped

It works, and it is a time bomb. When a third channel, push notifications, arrives, every function that picks a notifier needs another branch. The selection logic is duplicated, and each copy can disagree. A factory centralizes the decision.

A factory function

The simplest form is a function that returns the right object.

factory-function.mjsJavaScript
class EmailNotifier {
  send(to, text) {
    return `email to ${to}: ${text}`;
  }
}
class SmsNotifier {
  send(to, text) {
    return `sms to ${to}: ${text}`;
  }
}

export function createNotifier(channel) {
  switch (channel) {
    case "email":
      return new EmailNotifier();
    case "sms":
      return new SmsNotifier();
    default:
      throw new Error(`Unknown channel: ${channel}`);
  }
}

const notifier = createNotifier("sms");
console.log(notifier.send("+15550100", "Code 4821"));
try {
  createNotifier("fax");
} catch (err) {
  console.log(err.message);
}
Text
sms to +15550100: Code 4821
Unknown channel: fax

Callers now say createNotifier(user.channel) and use whatever comes back through the send(to, text) interface. The switch lives in one place. An unknown channel fails loudly at creation, not later at the first send. Strictly, the textbook name for this shape is a "simple factory", but it is what most JavaScript code means by a factory, and it is the right default.

The classic form: subclasses decide

The Gang of Four factory method puts the creation step in an overridable method, so a subclass chooses the product. It fits when a base class has an algorithm that needs an object whose type varies.

classic.mjsJavaScript
class Exporter {
  createWriter() {
    throw new Error("createWriter() must be implemented");
  }

  export(rows) {
    const writer = this.createWriter();
    return rows.map((row) => writer.write(row)).join("\n");
  }
}

class CsvWriter {
  write(row) {
    return Object.values(row).join(",");
  }
}
class JsonLineWriter {
  write(row) {
    return JSON.stringify(row);
  }
}

class CsvExporter extends Exporter {
  createWriter() {
    return new CsvWriter();
  }
}
class JsonLineExporter extends Exporter {
  createWriter() {
    return new JsonLineWriter();
  }
}

const rows = [{ id: 1, name: "Ada" }, { id: 2, name: "Grace" }];
console.log(new CsvExporter().export(rows));
console.log(new JsonLineExporter().export(rows));
Text
1,Ada
2,Grace
{"id":1,"name":"Ada"}
{"id":2,"name":"Grace"}

The export method, the template, is written once and calls this.createWriter(), the factory method. Each subclass supplies its product. The algorithm never names a concrete writer. In JavaScript, passing the factory as a function is usually lighter than subclassing.

functional.mjsJavaScript
class CsvWriter {
  write(row) {
    return Object.values(row).join(",");
  }
}

function exportRows(rows, createWriter) {
  const writer = createWriter();
  return rows.map((row) => writer.write(row)).join("\n");
}

console.log(exportRows([{ id: 1, name: "Ada" }], () => new CsvWriter()));
Text
1,Ada

Same decoupling, no class hierarchy. A function parameter is the idiomatic JavaScript replacement for the overridable method.

A registry: add a type without editing the factory

The switch still needs an edit for every new type. A registry turns the factory into data.

registry.mjsJavaScript
const creators = new Map();

export function registerNotifier(channel, create) {
  creators.set(channel, create);
}

export function createNotifier(channel, options = {}) {
  const create = creators.get(channel);
  if (!create) {
    throw new Error(`Unknown channel "${channel}". Known: ${[...creators.keys()].join(", ")}`);
  }
  return create(options);
}

registerNotifier("email", ({ from = "[email protected]" } = {}) => ({
  send: (to, text) => `email from ${from} to ${to}: ${text}`,
}));
registerNotifier("sms", () => ({ send: (to, text) => `sms to ${to}: ${text}` }));

console.log(createNotifier("email", { from: "[email protected]" }).send("[email protected]", "Hi"));
registerNotifier("push", () => ({ send: (to, text) => `push to ${to}: ${text}` }));
console.log(createNotifier("push").send("device-9", "Hi"));
try {
  createNotifier("fax");
} catch (err) {
  console.log(err.message);
}
Text
email from [email protected] to [email protected]: Hi
push to device-9: Hi
Unknown channel "fax". Known: email, sms, push

A new channel registers itself, perhaps from a plugin file, and the factory never changes. The error message lists the known channels, which turns a typo into a one-step fix. This is the open/closed principle in practice: open for extension, closed for modification.

Factories that validate and configure

A factory is also a good place for rules about how objects are built, so callers cannot construct them wrongly.

validating.mjsJavaScript
export function createUser({ name, email, role = "member" }) {
  if (!name?.trim()) throw new Error("name is required");
  if (!/^[^@\s]+@[^@\s]+$/.test(email ?? "")) throw new Error(`invalid email: ${email}`);
  if (!["member", "admin"].includes(role)) throw new Error(`invalid role: ${role}`);
  return Object.freeze({ name: name.trim(), email: email.toLowerCase(), role });
}

console.log(createUser({ name: " Ada ", email: "[email protected]" }));
try {
  createUser({ name: "Bob", email: "bob", role: "owner" });
} catch (err) {
  console.log(err.message);
}
Text
{ name: 'Ada', email: '[email protected]', role: 'member' }
invalid email: bob

Every user in the system passes through the same checks. If you also want the objects to be immutable, as here, the factory is where you freeze them.

Async factories

Constructors cannot be async, so objects that need asynchronous setup, such as a database client that connects, are created by an async factory.

async-factory.mjsJavaScript
class Client {
  #connected = false;
  static async connect(url) {
    await new Promise((resolve) => setTimeout(resolve, 5));
    const client = new Client();
    client.#connected = true;
    client.url = url;
    return client;
  }
  query(sql) {
    if (!this.#connected) throw new Error("not connected");
    return `ran "${sql}" on ${this.url}`;
  }
}

const client = await Client.connect("db://primary");
console.log(client.query("SELECT 1"));
Text
ran "SELECT 1" on db://primary

A static connect method returns a client that is ready to use. Nobody can hold a half-initialized Client, because the only way to get one is through the factory. This also removes a whole class of "forgot to call init()" bugs.

Testing

Factories help tests in two ways. A registry lets a test register a fake under the real name. And code that receives a factory as a parameter can be given a function that returns a stub.

test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";
import { registerNotifier, createNotifier } from "./registry.mjs";

test("notifications go to a fake channel", () => {
  const sent = [];
  registerNotifier("test", () => ({ send: (to, text) => sent.push({ to, text }) }));
  createNotifier("test").send("u1", "hello");
  assert.deepEqual(sent, [{ to: "u1", text: "hello" }]);
});
Text
✔ notifications go to a fake channel (0.8ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

When not to use it

If there is one concrete type and no realistic prospect of a second, a factory is a detour: new Mailer() is clearer. If the creation has no logic, new Foo(options) already is the factory. The pattern pays when the choice of type depends on data or configuration, when construction has rules or async steps, or when callers should not know about concrete classes. A rule of thumb: introduce a factory when you are about to copy a switch or an if chain that picks a class. See the abstract factory for creating families of related objects, and the builder when the object has many optional parts.

Recognizing it in libraries you use

Factories are everywhere in the JavaScript ecosystem, and spotting them makes the pattern feel less abstract. document.createElement("div") takes a string and returns the right element class. Array.from() and Promise.resolve() are static factory methods that build objects from varied inputs. Intl.NumberFormat and Intl.DateTimeFormat are created from a locale and options. Express's express() returns a configured application, and React's createElement and createContext produce objects whose concrete shape you never see. In each case the caller names what it wants and the library decides how to build it.

Reading these examples shows the conventions worth copying. Name factories with create, of, from or connect, so a reader knows construction happens inside. Validate arguments at the factory, so every created object satisfies the same rules. And return a stable interface, so callers depend on the methods and not on the class behind them.

Factory versus constructor: a short decision rule

A constructor is right when there is exactly one way to build the object and it cannot fail in interesting ways. Use a factory when you need a name for the construction, such as Money.fromCents, when the result's type depends on the input, when creation is asynchronous or when you want to return a cached or shared instance. A factory function can return an existing object, and a constructor cannot, so factories are also how you implement instance reuse and pooling.

Naming conventions worth following

A consistent vocabulary tells callers what they are getting. create suggests a new object every time. get suggests a possibly cached one. from and of suggest conversion from another representation. connect, open and load suggest asynchronous work with outside resources. Teams that settle on these words find that a call site communicates its cost and its identity guarantees without opening the definition, and that reviewers spot a create function that quietly returns a shared instance.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.