Design Patterns in JavaScript

Updated · 9 min read

A design pattern is a named, reusable solution to a problem that comes up again and again in software design. Patterns give teams a shared vocabulary ("let's use a strategy for the discount rules") and capture lessons learned the hard way. Many classic patterns were described for languages like Java and C++; in JavaScript, where functions are values and objects are flexible, most of them become small and simple, sometimes a single function. This lesson covers the patterns you'll use most, each with a Fee Tracker example and a note on when not to use it.

In One Minute

  • Module: private state with a public interface (ES modules, closures).
  • Factory: a function that creates and returns configured objects.
  • Observer (pub/sub): objects subscribe to events and get notified when something changes.
  • Strategy: interchangeable algorithms selected at run time (a lookup of functions).
  • Adapter: wraps an awkward interface so it matches the one your code expects.
  • Dependency injection: pass collaborators in instead of creating them inside.

Module

Problem: keep internal details private and expose only a small public interface. In JavaScript: ES modules do this natively (only exports are visible); closures do it inside a file.

module.js▶ Try it
function createReceiptCounter(prefix) {
  let next = 1001;
  const format = (n) => `${prefix}-${n}`;
  return {
    issue: () => format(next++),
    peek: () => format(next),
  };
}
 
const receipts = createReceiptCounter("R");
console.log(receipts.issue(), receipts.issue(), receipts.peek(), typeof receipts.next);
Output
R-1001 R-1002 R-1003 undefined

Don't use an extra closure wrapper when an ES module already gives you privacy; a module's unexported functions are private.

Factory

Problem: create objects whose exact type or setup depends on input, without callers knowing the details.

factory.js▶ Try it
class CardPayment { constructor(a) { this.amount = a; } fee() { return Math.round(this.amount * 2.9 + 30) / 100; } }
class AchPayment { constructor(a) { this.amount = a; } fee() { return Math.min(this.amount * 0.008, 5); } }
class CheckPayment { constructor(a) { this.amount = a; } fee() { return 0; } }
 
const TYPES = { card: CardPayment, ach: AchPayment, check: CheckPayment };
 
function createPayment(method, amount) {
  const Type = TYPES[method];
  if (!Type) throw new RangeError(`Unknown payment method: ${method}`);
  return new Type(amount);
}
 
for (const method of ["card", "ach", "check"]) console.log(method, createPayment(method, 120).fee());
Output
card 3.78
ach 0.96
check 0

Callers ask for "a card payment of $120" and get the right object. Adding a new method means adding one class and one table entry. Don't use a factory when a plain object literal or a single constructor is all you need.

Observer (Publish/Subscribe)

Problem: when something changes, several unrelated parts need to react, without the changing code knowing about them.

observer.js▶ Try it
function createEmitter() {
  const listeners = new Map();
  return {
    on(event, fn) {
      listeners.getOrInsert(event, new Set()).add(fn);
      return () => listeners.get(event).delete(fn);
    },
    emit(event, data) {
      for (const fn of listeners.get(event) ?? []) fn(data);
    },
  };
}
 
const bus = createEmitter();
bus.on("payment:recorded", (p) => console.log(`update totals: +$${p.amount}`));
const stopEmail = bus.on("payment:recorded", (p) => console.log(`email receipt to ${p.name}`));
 
bus.emit("payment:recorded", { name: "Navika", amount: 120 });
stopEmail();
bus.emit("payment:recorded", { name: "Advitha", amount: 45 });
Output
update totals: +$120
email receipt to Navika
update totals: +$45

The code that records payments just emits an event; totals, email and anything added later subscribe independently. on returns an unsubscribe function so listeners can be removed. The browser's EventTarget and Node.js's EventEmitter are built-in observers; you can also extends EventTarget in your own classes.

Don't use events for simple, direct calls between two parts: when A always needs B, calling B directly is clearer. Too many events make the flow hard to trace.

Strategy

Problem: several interchangeable ways of doing one thing (pricing rules, sort orders, export formats), chosen at run time. In JavaScript: a strategy is just a function; a set of strategies is an object of functions.

strategy.js▶ Try it
const discountStrategies = {
  none: (fee) => fee,
  sibling: (fee) => fee * 0.9,
  staff: (fee) => fee * 0.5,
  earlyBird: (fee, { paidBy, dueDate }) => (paidBy < dueDate ? fee - 25 : fee),
};
 
function finalFee(fee, strategy, context = {}) {
  const apply = discountStrategies[strategy] ?? discountStrategies.none;
  return Math.round(apply(fee, context) * 100) / 100;
}
 
console.log(finalFee(450, "sibling"), finalFee(450, "staff"));
console.log(finalFee(450, "earlyBird", { paidBy: "2026-01-02", dueDate: "2026-01-05" }), finalFee(450, "unknown"));
Output
405 225
425 450

New rules are added to the table without changing finalFee, and each strategy can be tested on its own. This replaces long if...else or switch chains.

Don't use strategies when there are only two simple variations; an if is fine.

Adapter

Problem: a library or API has a different interface from the one your code uses everywhere.

adapter.js▶ Try it
const legacyBillingApi = {
  getAcct: (id) => ({ ACCT_ID: id, CUST_NM: "SRIHITHA ANAMANENI", BAL_AMT_CENTS: "8500", LAST_PMT_DT: "20260105" }),
};
 
function toStudent(raw) {
  const d = raw.LAST_PMT_DT;
  return {
    id: raw.ACCT_ID,
    name: raw.CUST_NM.toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase()),
    balanceCents: Number(raw.BAL_AMT_CENTS),
    lastPayment: `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6)}`,
  };
}
 
console.log(toStudent(legacyBillingApi.getAcct("S-42")));
Output
{ id: 'S-42', name: 'Srihitha Anamaneni', balanceCents: 8500, lastPayment: '2026-01-05' }

The rest of the app sees clean, consistent Student objects; only the adapter knows the legacy format. When the old system is replaced, only the adapter changes. This is the pattern at the heart of integration work (and of the platform add-ons later in the course).

Dependency Injection

Problem: code that creates its own collaborators (new Database(), a global fetch) is hard to test and to reconfigure. Solution: pass collaborators in.

di.js▶ Try it
class ReminderService {
  constructor({ students, mailer, clock }) {
    this.students = students;
    this.mailer = mailer;
    this.clock = clock;
  }
  async sendDue() {
    const today = this.clock.today();
    const due = (await this.students.listOwing()).filter((s) => s.dueDate <= today);
    for (const s of due) await this.mailer.send(s.email, `Payment of $${s.balance} was due ${s.dueDate}`);
    return due.length;
  }
}
 
const sent = [];
const service = new ReminderService({
  students: { listOwing: async () => [{ email: "advitha@example.com", balance: 45, dueDate: "2026-01-01" }, { email: "zoe@example.com", balance: 20, dueDate: "2026-02-01" }] },
  mailer: { send: async (to, text) => sent.push(`${to}: ${text}`) },
  clock: { today: () => "2026-01-05" },
});
console.log(await service.sendDue(), sent);
Output
1 ['advitha@example.com: Payment of $45 was due 2026-01-01']

In production, main.js passes the real student repository, email client and system clock. In tests, simple fakes. No framework is required: passing arguments is dependency injection.

Patterns at a Glance

PatternUse whenJavaScript form
ModuleHiding internalsES module exports, closures
FactoryCreating varied objects from inputA function returning objects, a class lookup table
SingletonExactly one shared instanceA module's exported object (modules run once)
ObserverMany parts react to changesEventTarget, an emitter, signals
StrategyInterchangeable algorithmsAn object of functions
AdapterMismatched interfacesA converting function or wrapper object
DecoratorAdding behavior around a functionA higher-order function (withLogging(fn))
Dependency injectionTestability and configurabilityConstructor or function parameters

When Not to Use Patterns

Patterns solve problems; without the problem, they're just extra code. Warning signs: a factory that only ever creates one kind of object, an event bus for two components that always talk to each other, layers of wrappers with no behavior. Start with the simplest code that works, and introduce a pattern when the problem it solves actually appears (a second variation, a second listener, a test that needs a fake).

In Practice

The Fee Tracker's export feature combines three patterns: a strategy per format, a factory that picks one, and an observer that reports progress:

export.js▶ Try it
const exporters = {
  csv: (rows) => ["name,amount", ...rows.map((r) => `${r.name},${r.amount}`)].join("\n"),
  json: (rows) => JSON.stringify(rows),
  text: (rows) => rows.map((r) => `${r.name.padEnd(9)}$${r.amount}`).join("\n"),
};
 
function createExporter(format, onProgress = () => {}) {
  const run = exporters[format];
  if (!run) throw new RangeError(`Unsupported format: ${format}`);
  return (rows) => {
    onProgress(`exporting ${rows.length} rows as ${format}`);
    const output = run(rows);
    onProgress(`done (${output.length} characters)`);
    return output;
  };
}
 
const rows = [{ name: "Navika", amount: 120 }, { name: "Advitha", amount: 45 }];
const exportCsv = createExporter("csv", (msg) => console.log("progress:", msg));
console.log(exportCsv(rows));
console.log(createExporter("text")(rows));
Output
progress: exporting 2 rows as csv
progress: done (33 characters)
name,amount
Navika,120
Advitha,45
Navika   $120
Advitha  $45

Common Mistakes

Applying patterns everywhere. Add one when its problem appears, not in advance.

Forgetting to unsubscribe observers. Leaks and stale updates. Keep the unsubscribe function.

Copying Java-style class hierarchies. In JavaScript, functions and objects are usually simpler.

Global singletons that hide dependencies. Prefer passing collaborators in.

Interview Corner

Explain the observer pattern and give a JavaScript example.

Subjects keep a list of subscribers and notify them when something happens, so producers and consumers stay decoupled. In JavaScript: addEventListener on DOM elements, Node.js EventEmitter, EventTarget, RxJS observables, and framework signals. Subscriptions must be removed to avoid leaks.

What is dependency injection, and why does it help testing?

Supplying a component's collaborators from outside (constructor or function parameters) instead of having it create or import them directly. Tests can pass fakes (an in-memory store, a fixed clock), and production can swap implementations without changing the component.

Practice

Challenge: Implement a withRetry(fn, times) decorator: a higher-order function that returns a new async function which calls fn and retries up to times times if it throws.

Show solution
decorator.js▶ Try it
function withRetry(fn, times) {
  return async (...args) => {
    for (let attempt = 0; ; attempt++) {
      try {
        return await fn(...args);
      } catch (err) {
        if (attempt >= times) throw err;
      }
    }
  };
}
 
let calls = 0;
const flaky = async (x) => { calls++; if (calls < 3) throw new Error("temporary"); return x * 2; };
console.log(await withRetry(flaky, 3)(21), "after", calls, "calls");
Output
42 after 3 calls

Quick check: Design patterns

3 questions
1Which pattern replaces a long switch over discount types with an object of functions?
2What does an adapter do?
3How is a singleton usually expressed in modern JavaScript?

Key Takeaways

NeedPattern
Hide internalsModule
Create the right objectFactory
React to changesObserver
Swap algorithmsStrategy
Translate an APIAdapter
Testable collaboratorsDependency injection

Was this tutorial helpful?

Lesson 131 of 139