JavaScript Design Patterns Every Developer Should Know
Learn the most useful JavaScript design patterns with modern ES6+ code: module, singleton, factory, observer, pub/sub, strategy, decorator, proxy and more, plus when not to use them.
A design pattern is a reusable solution to a problem that keeps coming up in software. Patterns give teams a shared vocabulary: saying "use an observer here" communicates a whole design in three words. JavaScript's first-class functions and closures make many classic patterns much lighter than in Java or C#.
The three families of patterns#
- Creational patterns control how objects are created.
- Structural patterns control how objects are composed.
- Behavioral patterns control how objects communicate.
Creational patterns#
Module pattern#
Modules hide private state and expose a public API. Before ES modules, this was done with an IIFE and a closure. Today, the file itself is the module.
// cart.js
const items = []; // private: not exported
export function addItem(item) {
items.push(item);
}
export function total() {
return items.reduce((sum, i) => sum + i.price * i.qty, 0);
}Singleton#
One shared instance for the whole app, such as a config object or a database connection. ES modules are evaluated once and cached, so exporting an instance is already a singleton:
// logger.js
class Logger {
#logs = [];
log(msg) {
this.#logs.push({ msg, at: Date.now() });
console.log(`[LOG] ${msg}`);
}
get count() { return this.#logs.length; }
}
export const logger = new Logger(); // every import gets the same objectSingletons are global state in disguise. They make tests harder because state leaks between test cases. Prefer passing dependencies in where you can.
Factory#
A factory creates objects without the caller needing to know the exact class.
class EmailNotifier { send(msg) { /* ... */ } }
class SmsNotifier { send(msg) { /* ... */ } }
class PushNotifier { send(msg) { /* ... */ } }
const notifiers = { email: EmailNotifier, sms: SmsNotifier, push: PushNotifier };
export function createNotifier(type) {
const Notifier = notifiers[type];
if (!Notifier) throw new Error(`Unknown notifier: ${type}`);
return new Notifier();
}
createNotifier("sms").send("Your OTP is 4821");Builder#
Useful when an object has many optional parts. Method chaining keeps it readable:
class QueryBuilder {
#parts = { table: "", where: [], limit: null };
from(table) { this.#parts.table = table; return this; }
where(cond) { this.#parts.where.push(cond); return this; }
limit(n) { this.#parts.limit = n; return this; }
build() {
const { table, where, limit } = this.#parts;
let sql = `SELECT * FROM ${table}`;
if (where.length) sql += ` WHERE ${where.join(" AND ")}`;
if (limit) sql += ` LIMIT ${limit}`;
return sql;
}
}
new QueryBuilder().from("users").where("age > 18").limit(10).build();Structural patterns#
Decorator#
A decorator wraps something to add behaviour without changing it. In JavaScript, higher-order functions are decorators:
function withTiming(fn) {
return async function (...args) {
const start = performance.now();
try {
return await fn.apply(this, args);
} finally {
console.log(`${fn.name} took ${(performance.now() - start).toFixed(1)}ms`);
}
};
}
const fetchUser = withTiming(async function fetchUser(id) {
const res = await fetch(`/api/users/${id}`);
return res.json();
});Proxy#
The built-in Proxy object intercepts operations on another object. It's how Vue 3 tracks reactive state.
function createValidated(target, schema) {
return new Proxy(target, {
set(obj, key, value) {
if (schema[key] && typeof value !== schema[key]) {
throw new TypeError(`${key} must be a ${schema[key]}`);
}
obj[key] = value;
return true;
},
});
}
const user = createValidated({}, { age: "number", name: "string" });
user.name = "Asha"; // ok
user.age = "twenty"; // TypeError: age must be a numberAdapter#
An adapter converts one interface into another so incompatible code can work together, for example wrapping an old callback API in a promise:
import { readFile } from "node:fs";
const readFileAsync = (path) =>
new Promise((resolve, reject) =>
readFile(path, "utf8", (err, data) => (err ? reject(err) : resolve(data)))
);
// (Node already ships this as fs/promises, but the idea applies to any legacy API.)Facade#
A facade gives a simple front to a complex subsystem: one checkout() call that internally validates the cart, charges payment, reserves stock and sends an email.
Behavioral patterns#
Observer#
An object (the subject) keeps a list of listeners and notifies them when something changes. DOM events, Node's EventEmitter and RxJS are all observers.
class Store {
#state;
#listeners = new Set();
constructor(initial) { this.#state = initial; }
getState() { return this.#state; }
setState(update) {
this.#state = { ...this.#state, ...update };
this.#listeners.forEach((fn) => fn(this.#state));
}
subscribe(fn) {
this.#listeners.add(fn);
return () => this.#listeners.delete(fn); // unsubscribe function
}
}
const store = new Store({ count: 0 });
const unsubscribe = store.subscribe((s) => console.log("count is", s.count));
store.setState({ count: 1 }); // count is 1
unsubscribe();This is the core idea behind Redux, Zustand and most state libraries.
Pub/Sub#
Like observer, but publishers and subscribers don't know about each other. They only share a topic name through an event bus:
const bus = {
topics: new Map(),
on(topic, fn) {
if (!this.topics.has(topic)) this.topics.set(topic, new Set());
this.topics.get(topic).add(fn);
},
emit(topic, data) {
this.topics.get(topic)?.forEach((fn) => fn(data));
},
};
bus.on("order:placed", (o) => sendEmail(o));
bus.on("order:placed", (o) => updateAnalytics(o));
bus.emit("order:placed", { id: 42, total: 999 });At system scale, this same idea becomes a message broker. See message queues: Kafka vs RabbitMQ.
Strategy#
Swap an algorithm at runtime. In JavaScript, a strategy is usually just an object of functions:
const shipping = {
standard: (weight) => 40 + weight * 5,
express: (weight) => 100 + weight * 8,
free: () => 0,
};
function shippingCost(method, weight) {
return shipping[method](weight);
}
shippingCost("express", 2); // 116This replaces long if/else or switch chains and makes adding a new option a one-line change.
Command#
Wrap an action in an object so you can queue it, log it or undo it. Text editors use this for undo/redo:
const history = [];
function execute(command) {
command.do();
history.push(command);
}
function undo() {
history.pop()?.undo();
}
execute({ do: () => doc.insert("Hi"), undo: () => doc.delete(2) });
undo();Choosing the right pattern#
| Problem | Pattern |
|---|---|
| Hide internals, expose an API | Module |
| Create different objects from one entry point | Factory |
| Add logging, caching or timing to a function | Decorator |
| Validate or track property access | Proxy |
| React to state changes | Observer |
| Decouple features that react to the same event | Pub/Sub |
| Replace a big switch on "type" | Strategy |
| Undo/redo, job queues | Command |
Don't start with a pattern. Write the simplest code, and reach for a pattern when you feel the pain it solves. Unneeded abstraction is harder to read than a plain function.
Decorators are a natural fit for rate-limiting user input; see debounce vs throttle. Observers that never unsubscribe are a common source of JavaScript memory leaks.
Key takeaways#
- Patterns fall into creational, structural and behavioral families.
- ES modules give you the module and singleton patterns for free.
- Higher-order functions are JavaScript's natural decorators;
Proxyintercepts object operations. - Observer and pub/sub power state management and event-driven code.
- Strategy objects replace long conditionals; use any pattern only when it removes real pain.