What is the Strategy pattern?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
The Strategy pattern puts each variant of an algorithm behind the same interface so callers can swap between them without knowing the details. The signal that you need it is a growing if/else or switch that picks behaviour based on a type or mode.
// before — every new option means editing this function
function getPrice(order, type) {
if (type === "member") return order.total * 0.9;
if (type === "seasonal") return order.total - 10;
return order.total;
}
In JavaScript a strategy is usually just a function, so the pattern collapses into a lookup table:
const pricing = {
standard: (order) => order.total,
member: (order) => order.total * 0.9,
seasonal: (order) => order.total - 10,
};
function getPrice(order, type) {
const strategy = pricing[type] ?? pricing.standard;
return strategy(order);
}
Adding a rule now means adding one entry, not editing the function — the open/closed principle in practice. Each strategy is also trivially testable on its own, and can be chosen at runtime from config or a feature flag.
In class form
When strategies need their own state, objects sharing a method name do the same job:
class Sorter {
constructor(strategy) { this.strategy = strategy; }
sort(data) { return this.strategy.run(data); }
}
const byDate = { run: (d) => [...d].sort((a, b) => a.date - b.date) };
new Sorter(byDate).sort(items);
When not to bother
Two branches that will never grow are clearer as an if. The pattern earns its keep when variants keep appearing, when they need testing in isolation, or when the choice is made at runtime. Do not introduce the indirection before that — a lookup table with two entries is harder to read than the conditional it replaced.
