What are common JavaScript design patterns
· Category: JavaScript
Short answer
Design patterns provide reusable solutions to common problems. Key patterns in JavaScript include Module, Singleton, Factory, Observer, and Decorator.
Steps
- Module pattern: Encapsulate private state.
javascript const counter = (() => { let count = 0; return { increment: () => ++count }; })(); - Singleton: Ensure one instance.
javascript class Config { static #instance; static getInstance() { return this.#instance ??= new Config(); } } - Factory: Create objects without specifying the exact class.
javascript function createUser(type) { if (type === "admin") return new Admin(); return new User(); } - Observer: Subscribe and notify listeners.
javascript class EventBus { #listeners = new Map(); on(event, fn) { /* ... */ } emit(event, data) { /* ... */ } }
Tips
- Prefer composition over inheritance.
- Use patterns when they simplify code, not for the sake of using them.
Common issues
- Singletons make unit testing harder because of global state.
- Overusing the Observer pattern creates memory leaks if listeners are not removed.