# JavaScript Design Patterns

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

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-design-patterns
Last updated: 2026-11-28

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

- **Module**: before ES2015 this was an IIFE returning an object, with private variables kept in the closure. Today every ES module file is a module: anything not exported is private. This is the most widely used pattern in JavaScript, often without people naming it.
- **Singleton**: a single shared instance, such as a database connection pool, a logger or an analytics client. In JS the simplest singleton is an object exported from a module, because modules are evaluated once and cached. Downsides: hidden global state and harder testing, so prefer passing dependencies in where you can.
- **Factory**: a function that returns objects, choosing the concrete type based on input. Example: `createPaymentProvider('upi')` returning a UPI handler versus a card handler. React's `createElement` and Node's `http.createServer` are factories.

### Behavioural patterns: Observer and Strategy

- **Observer**: a subject keeps a list of listeners and notifies them on change. The DOM's `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.
- **Strategy**: define a family of algorithms with the same interface and pick one at runtime. In JS this is often just an object map of functions: `discountStrategies[coupon.type](cart)`. It replaces long `if/else` or `switch` chains and makes adding a new rule a one-line change.

### Structural patterns: Decorator, Proxy, Facade

- **Decorator**: wrap a function or object to add behaviour without changing it. Higher-order functions like `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**: control access to another object (lazy loading, caching, validation). JavaScript has a built-in `Proxy` for this.
- **Facade**: a simple API over a complex subsystem, for example an `api.js` wrapper hiding `fetch`, auth headers, retries and error mapping.

### Choosing and avoiding patterns

| 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.

**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

- ES modules are the built-in Module pattern and give you singletons for free because they are evaluated once.
- Factory functions create objects without the caller knowing the concrete type.
- Observer underlies addEventListener, EventEmitter, RxJS and store.subscribe.
- Strategy replaces switch statements with a map of interchangeable functions.
- Decorators (higher-order functions, middleware, HOCs) add behaviour without modifying the original.

## Common follow-up questions

- What are the downsides of the Singleton pattern, especially for testing?
- How is Pub/Sub different from Observer?
- How would you implement middleware like Express using the Decorator or Chain of Responsibility pattern?
- Which patterns does React use internally or encourage?
- How would you avoid memory leaks in an Observer implementation?

## Interview tips

- For each pattern, give a real example you have used or a well-known API that uses it.
- Show that you know JavaScript makes many patterns lighter, such as modules as singletons and functions as strategies.
- Avoid listing every Gang of Four pattern; depth on four or five beats a shallow list of twenty.

## Concepts covered

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

Previous: [Deep Cloning: structuredClone vs JSON](https://www.internhack.in/learn/interview/javascript-interview/js-structuredclone) · Next: [Memory Leaks in JavaScript](https://www.internhack.in/learn/interview/javascript-interview/js-memory-leaks) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Custom Error Types and Error Handling](https://www.internhack.in/learn/interview/javascript-interview/js-error-types)
- [WebSockets and Real-time Communication](https://www.internhack.in/learn/interview/javascript-interview/js-websockets)
- [Advanced Regular Expressions](https://www.internhack.in/learn/interview/javascript-interview/js-regex-advanced)
- [JavaScript Performance Optimization](https://www.internhack.in/learn/interview/javascript-interview/js-performance-optimization)
- [Tagged Template Literals](https://www.internhack.in/learn/interview/javascript-interview/js-tagged-templates)
- [Intersection Observer and Mutation Observer](https://www.internhack.in/learn/interview/javascript-interview/js-intersection-observer)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
