QuestionsJavaScript

Strategy — interchangeable algorithms

Behavioral PatternsMediumJavaScript

Implement the Strategy pattern. How does it replace conditional logic with pluggable, swappable behavior?

What it tests

Spotting the growing if/switch-on-type smell and refactoring branches into a map of interchangeable strategy functions selected at runtime.

Approach & answer

Strategy defines a family of interchangeable algorithms, encapsulates each one, and makes them swappable at runtime behind a common interface — so the choice of algorithm is data, not a hard-coded branch. The signal: a function that keeps growing a `switch`/`if-else` on a 'type' or 'mode', where each branch is a self-contained algorithm — shipping-cost by carrier, validation by field type, pricing by customer tier, sort by strategy, export by format. Each new case means editing that one big function (violating Open/Closed) and the branches tend to share nothing. Strategy refactors each branch into its own function (the strategy), stores them in a map keyed by the selector, and the context just looks up and delegates: `strategies[key](input)`. Now adding a behavior means adding a map entry — no existing code changes — and each strategy is independently testable. In JavaScript strategies are usually just functions (no need for classes/interfaces), which makes this pattern especially lightweight: a plain object of functions IS the strategy set. It's the backbone of countless frontend features — form validators, comparator functions passed to `sort`, formatting/serialization by type, and configurable behaviors injected as props/callbacks. Strategy vs State (js-43): both swap behavior via composition, but Strategy is chosen by the CLIENT for a one-shot operation and strategies don't know about each other, whereas State transitions are driven internally by the object as it moves between states. Reach for Strategy the moment a conditional is really 'which algorithm', and skip it for a single stable branch.

Use this technique when

A conditional selects among self-contained algorithms — validators, formatters, comparators, pricing/shipping rules, export formats — especially when new variants are added often.

Complexity

O(1) lookup + the chosen strategy's own cost.

References

js