What are design patterns?

JavaScript

The short answer

Design patterns are reusable solutions to common problems in software development. They are not code you copy-paste — they are templates for how to solve a specific type of problem. Knowing them helps you write better-organized code and communicate solutions with other developers using a shared vocabulary.

The three categories

Design patterns are traditionally grouped into three types:

Creational — how objects are created:

  • Factory — creates objects without specifying the exact class
  • Singleton — ensures only one instance exists
  • Prototype — creates objects by cloning existing ones

Structural — how objects are composed together:

  • Decorator — adds behavior to objects without modifying them
  • Module — encapsulates code with private and public parts
  • Proxy — controls access to an object

Behavioral — how objects communicate:

  • Observer — one object notifies many others when it changes
  • Strategy — swaps algorithms at runtime
  • Command — turns operations into objects (enables undo/redo)

Patterns you already use in JavaScript

Observer pattern — event listeners:

button.addEventListener('click', handleClick);
// The button (subject) notifies the handler (observer) when clicked

Strategy pattern — array sort with different comparators:

items.sort((a, b) => a.price - b.price); // sort by price
items.sort((a, b) => a.name.localeCompare(b.name)); // sort by name

Factory pattern — React.createElement:

// JSX is transformed into createElement calls — a factory
React.createElement('div', { className: 'box' }, 'Hello');

Module pattern — ES6 modules:

// Private to this file
let count = 0;
// Public API
export function increment() {
count += 1;
}

Why they matter

  • Communication — "Let's use the observer pattern here" is faster than explaining the entire solution
  • Proven solutions — these patterns have been tested and refined over decades
  • Better architecture — they help you organize code in maintainable ways

Interview Tip

You do not need to memorize all design patterns. Focus on the ones you use in everyday JavaScript and React: Observer (events), Factory (object creation), Strategy (swapping algorithms), Decorator (HOCs, middleware), and Module (ES6 modules). If you can explain three or four with practical examples, that is a strong answer.

Why interviewers ask this

Interviewers ask about design patterns to see if you can think about code at a structural level, not just write it line by line. Knowing patterns shows you can design solutions that are maintainable and communicate your ideas effectively with other developers.