JavaScript Design Patterns

Difficulty: Intermediate

Question

What design patterns are commonly used in JavaScript applications? Explain the Module, Singleton, Factory, Observer and Strategy patterns with examples.

Answer

Design patterns are reusable solutions to recurring design problems. In JavaScript the most common ones are Module (encapsulate private state and expose a public API), Singleton (one shared instance), Factory (create objects without exposing construction details), Observer or Pub/Sub (notify subscribers when something happens) and Strategy (swap interchangeable algorithms at runtime). Because JavaScript has first-class functions, closures and ES modules, many classic Gang of Four patterns become much lighter than their Java versions.

Creational patterns: Module, Singleton, Factory

Behavioural patterns: Observer and Strategy

Structural patterns: Decorator, Proxy, Facade

Choosing and avoiding patterns

ProblemPattern
Hide internals, expose a small APIModule
Exactly one shared resourceSingleton (module export)
Create one of several related typesFactory
React to events or state changesObserver / Pub-Sub
Swap business rules at runtimeStrategy
Add cross-cutting behaviour (logging, retries)Decorator

Patterns are vocabulary, not goals. Overusing them, for example wrapping every class in a factory or making everything a singleton, adds indirection without benefit. In interviews, explaining why a pattern fits a specific problem is worth more than reciting definitions.

The Observer pattern as an event emitter. Subscribe, unsubscribe and emit in any order under Tweak.
  1. Subject keeps subscribers: on() adds a callback; off() removes it.
  2. emit notifies all: Every current subscriber is called, in order.
  3. once: A wrapper removes itself after the first event.
  4. Decoupling: Publishers don't know who listens. Unsubscribe to avoid leaks.

Code examples

Observer with a minimal EventEmitter

class EventEmitter {
  #listeners = new Map();

  on(event, fn) {
    if (!this.#listeners.has(event)) this.#listeners.set(event, new Set());
    this.#listeners.get(event).add(fn);
    return () => this.#listeners.get(event).delete(fn); // unsubscribe
  }

  emit(event, payload) {
    this.#listeners.get(event)?.forEach(fn => fn(payload));
  }
}

const orders = new EventEmitter();
const stopSms = orders.on('placed', o => console.log(`SMS: order ${o.id} placed`));
orders.on('placed', o => console.log(`Kitchen: start ${o.item}`));

orders.emit('placed', { id: 101, item: 'Biryani' });
stopSms();
orders.emit('placed', { id: 102, item: 'Dosa' });

Subscribers register callbacks and the emitter notifies all of them, without the emitter knowing what they do. Returning an unsubscribe function avoids leaked listeners.

Strategy, Factory and module Singleton together

// Strategy: interchangeable discount rules with the same signature
const discountStrategies = {
  flat: (total, c) => Math.max(total - c.value, 0),
  percent: (total, c) => total - Math.min(total * c.value / 100, c.cap ?? Infinity),
  none: total => total,
};

// Factory: build a coupon object from raw API data
function createCoupon({ code, type, value, cap }) {
  const apply = discountStrategies[type] ?? discountStrategies.none;
  return { code, apply: total => apply(total, { value, cap }) };
}

// Singleton: modules are cached, so this one instance is shared app-wide
const couponRegistry = (() => {
  const coupons = new Map();
  return { add: c => coupons.set(c.code, c), get: code => coupons.get(code) };
})();

couponRegistry.add(createCoupon({ code: 'FLAT100', type: 'flat', value: 100 }));
couponRegistry.add(createCoupon({ code: 'SAVE20', type: 'percent', value: 20, cap: 150 }));

console.log(couponRegistry.get('FLAT100').apply(599));
console.log(couponRegistry.get('SAVE20').apply(599));
console.log(couponRegistry.get('SAVE20').apply(1200));

New discount types are added by registering a strategy, not by editing a switch statement. The factory hides how coupons are assembled, and the IIFE-based registry is a single shared instance with private state.

Key points

Common follow-up questions

Interview tips

Concepts covered

Module Pattern, Singleton, Factory, Observer, Strategy, Decorator

More JavaScript Interview questions