JavaScript › Design Patterns in JavaScript
What is the Strategy pattern and how does it help avoid large if/else chains?
AdvancedAnswer
Strategy defines a family of interchangeable algorithms/behaviors as separate functions or objects, and lets you swap which one is used at runtime, replacing sprawling conditional logic with a simple lookup or injected dependency.
const strategies = {
card: (amt) => payWithCard(amt),
paypal: (amt) => payWithPaypal(amt),
};
function pay(method, amount) {
return strategies[method](amount);
}Real-world example Supporting multiple payment or shipping calculation methods that can be swapped without touching the core checkout logic.