What is the strategy pattern in JavaScript?
The strategy pattern lets you swap an algorithm at runtime by storing interchangeable functions ("strategies") and picking one as needed.
Interchangeable — each strategy follows the same interface, so they're swappable.
Removes conditionals — replace big if/else or switch blocks with a lookup of strategies.
In JavaScript: an object mapping names to functions is the simplest strategy pattern.
// Strategies as functions
const strategies = {
standard: (price) => price,
premium: (price) => price * 0.9, // 10% discount
vip: (price) => price * 0.8, // 20% discount
employee: (price) => price * 0.5 // 50% discount
};
function calculatePrice(price, customerType) {
const strategy = strategies[customerType] || strategies.standard;
return strategy(price);
}
console.log(calculatePrice(100, 'premium')); // 90
console.log(calculatePrice(100, 'vip')); // 80
console.log(calculatePrice(100, 'employee')); // 50
// Adding a new strategy — no changes to calculatePrice
strategies.blackfriday = (price) => price * 0.7; // 30% off
console.log(calculatePrice(100, 'blackfriday')); // 70Strategies are functions in an object — calculatePrice delegates to the selected strategy. Adding a new strategy (blackfriday) requires only adding to the strategies object — no changes to the calculation logic.
This is the Open/Closed Principle: open for extension (new strategies), closed for modification (calculatePrice unchanged).
In JS, strategies are just functions (no class hierarchy needed). Show the pricing example — it is practical and relatable.
The key: adding strategies does not require changing the consumer (Open/Closed Principle). First-class functions make the strategy pattern trivially clean in JS.