Difficulty: Intermediate
What design patterns are commonly used in JavaScript applications? Explain the Module, Singleton, Factory, Observer and Strategy patterns with examples.
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.
createPaymentProvider('upi') returning a UPI handler versus a card handler. React's createElement and Node's http.createServer are factories.addEventListener, Node's EventEmitter, RxJS observables, and state libraries like Redux (store.subscribe) are all Observer. Pub/Sub is a variant where publishers and subscribers communicate through a broker or channel name and do not know about each other.discountStrategies[coupon.type](cart). It replaces long if/else or switch chains and makes adding a new rule a one-line change.withRetry(fetchOrder), Express middleware and React higher-order components are decorators. TC39 decorators (@logged) reached Stage 3 and are supported by TypeScript 5.0+, with native engine support still rolling out.Proxy for this.api.js wrapper hiding fetch, auth headers, retries and error mapping.| Problem | Pattern |
|---|---|
| Hide internals, expose a small API | Module |
| Exactly one shared resource | Singleton (module export) |
| Create one of several related types | Factory |
| React to events or state changes | Observer / Pub-Sub |
| Swap business rules at runtime | Strategy |
| 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.
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: 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.
Module Pattern, Singleton, Factory, Observer, Strategy, Decorator