A design pattern is a named, reusable solution to a recurring design problem: not code to copy, but a template you adapt. Patterns are useful because they give teams a shared vocabulary ("make it an observer", "use a strategy here"), capture proven trade-offs, and lead to code that's easier to extend and test. In JavaScript, many classic patterns are simpler than their textbook form thanks to first-class functions, closures and modules, and some are built into the language or frameworks.
| Category | Problem | Examples |
|---|---|---|
| Creational | How objects get created | Factory, Singleton, Builder, Prototype |
| Structural | How objects are composed | Decorator, Adapter, Facade, Proxy, Composite |
| Behavioural | How objects communicate | Observer, Strategy, Command, Iterator, State, Mediator |
Plus JavaScript/front-end-specific patterns: Module, Mixin, Pub/Sub, Provider, Hooks, Render props / compound components, Container/presentational, Flux/unidirectional data flow, and architectural patterns like MVC/MVVM and micro-frontends.
button.addEventListener('click', onClick); // Observer
const sorted = items.toSorted(byPrice); // Strategy (comparator function)
for (const x of new Set(list)) {} // Iterator protocol
const p = new Proxy(target, handler); // Proxy (built into the language)
export const config = loadConfig(); // Module + singleton instance
const withAuth = (Component) => (props) => …; // Decorator (higher-order component)
// before: every new payment method edits this function
function pay(method, amount) {
if (method === 'card') return chargeCard(amount);
if (method === 'paypal') return redirectToPaypal(amount);
if (method === 'upi') return requestUpi(amount);
throw new Error('Unknown method');
}
// after: register strategies; adding one doesn't touch existing code
const paymentStrategies = {
card: chargeCard,
paypal: redirectToPaypal,
upi: requestUpi,
};
const pay = (method, amount) => {
const strategy = paymentStrategies[method];
if (!strategy) throw new Error(`Unknown payment method: ${method}`);
return strategy(amount);
};
Spotted a mistake or a rights concern? Report an issue