Design Patterns 🧩
Patterns are reusable blueprints for common problems. Here are the most practical ones in JavaScript.
1) Module Pattern 📦
Encapsulate private variables with an IIFE and expose a public API.
const cartModule = (() => {
const items = [];
function add(product) { items.push(product); }
function total() { return items.reduce((sum, item) => sum + item.price, 0); }
return { add, total };
})();2) Revealing Module 🌤️
Return references to private functions directly for clarity.
const userStore = (() => {
const users = new Map();
const addUser = user => users.set(user.id, user);
const getUser = id => users.get(id);
return { addUser, getUser };
})();3) Factory Pattern 🏭
Create objects through a function instead of using new directly.
function createUser(role) {
const base = { active: true };
return role === "admin"
? { ...base, permissions: ["read", "write", "delete"] }
: { ...base, permissions: ["read"] };
}4) Singleton Pattern 👑
Ensure only one instance exists.
class Config {
constructor(settings) {
if (Config.instance) return Config.instance;
this.settings = settings;
Config.instance = this;
}
}5) Observer Pattern 👀
Subscribe/unsubscribe to state changes.
class Observable {
constructor() { this.subscribers = new Set(); }
subscribe(fn) { this.subscribers.add(fn); return () => this.subscribers.delete(fn); }
notify(value) { this.subscribers.forEach(fn => fn(value)); }
}
const store = new Observable();
store.subscribe(console.log);
store.notify("updated");6) Strategy Pattern 🎯
Switch algorithms at runtime via interchangeable functions.
const strategies = {
percentage: amount => amount * 0.1,
flat: amount => 5
};
function calculateTax(amount, strategyName) {
const strategy = strategies[strategyName];
return strategy(amount);
}Key Takeaways ✅
- Modules keep state private; factories and singletons control instance creation.
- Observer powers pub/sub systems; strategy swaps behavior without branching everywhere.
- Patterns should solve real pain points—avoid over-engineering small scripts.
Recap 🔄
Apply patterns when they reduce duplication or clarify structure: modularize state, centralize creation, and pick observers/strategies for dynamic flows.
Last updated on