The Strategy Pattern in JavaScript, With Real Examples
The strategy pattern swaps an algorithm at runtime behind one interface. See pricing, sorting and retry strategies in JavaScript as functions and classes.

The strategy pattern defines a family of interchangeable algorithms behind one interface and lets the caller pick which to use. The code that needs the algorithm, the context, does not contain the choice: it receives a strategy and calls it. In JavaScript the pattern is almost invisible, because functions are values, so a strategy is usually just a function you pass in. Array.prototype.sort(compareFn) is a strategy parameter. Passport's authentication strategies are the pattern with the name on it. This post covers the pattern in JavaScript on Node.js 24 starting from the conditional it replaces, through function strategies, a lookup table, class strategies that carry state, and TypeScript, and compares it with state and factory, which look alike. Every sample prints its output.
The problem: a growing conditional
A shop calculates shipping by method.
function shipping(order, method) {
if (method === "standard") return order.weightKg * 1.5;
if (method === "express") return 10 + order.weightKg * 3;
if (method === "pickup") return 0;
throw new Error(`Unknown method: ${method}`);
}
console.log(shipping({ weightKg: 4 }, "standard"));
console.log(shipping({ weightKg: 4 }, "express"));
console.log(shipping({ weightKg: 4 }, "pickup"));6
22
0Each new method edits this function, the rules for all methods live in one block and testing one method means going through the same function. When methods gain parameters, such as a free-shipping threshold or a regional surcharge, the function becomes hard to follow. The strategy pattern moves each algorithm out.
Functions as strategies
In JavaScript, the lightest version is a function per algorithm and a context that takes one.
const standard = (order) => order.weightKg * 1.5;
const express = (order) => 10 + order.weightKg * 3;
const pickup = () => 0;
function checkoutTotal(order, shippingStrategy) {
return order.subtotal + shippingStrategy(order);
}
const order = { subtotal: 50, weightKg: 4 };
console.log(checkoutTotal(order, standard));
console.log(checkoutTotal(order, express));
console.log(checkoutTotal(order, pickup));
console.log(checkoutTotal(order, (o) => (o.subtotal > 40 ? 0 : 5)));56
72
50
50checkoutTotal knows nothing about methods. The caller chooses the strategy, and can even pass a one-off function inline, as in the last call that gives free shipping above a subtotal. The interface is "takes an order, returns a number", which is the whole contract. No class, no interface declaration.
A lookup table for named strategies
When the choice comes from data, such as a user's selection or a configuration value, keep the strategies in an object and look them up by name.
const shippingStrategies = {
standard: (order) => order.weightKg * 1.5,
express: (order) => 10 + order.weightKg * 3,
pickup: () => 0,
};
export function shippingCost(order, method) {
const strategy = shippingStrategies[method];
if (!strategy) {
throw new Error(`Unknown method "${method}". Choose one of: ${Object.keys(shippingStrategies).join(", ")}`);
}
return strategy(order);
}
console.log(shippingCost({ weightKg: 2 }, "express"));
try {
shippingCost({ weightKg: 2 }, "drone");
} catch (err) {
console.log(err.message);
}16
Unknown method "drone". Choose one of: standard, express, pickupAdding a method is one entry in the table. The table is a registry, which is the same shape the factory pattern uses to make objects. One caution: shippingStrategies[method] with a user-supplied key can match inherited properties such as toString or constructor. Use Object.hasOwn(shippingStrategies, method), a Map, or Object.create(null) when keys come from untrusted input.
const strategies = { standard: () => 1 };
const key = "toString";
console.log(typeof strategies[key]);
console.log(Object.hasOwn(strategies, key));function
falsestrategies["toString"] found a function on Object.prototype, which would be called as though it were a strategy. Object.hasOwn is available in Node.js 16.9 and later and checks only own properties.
Strategies that carry configuration
A strategy that needs parameters is a function that returns a function, or an object. Closures keep the setup tidy.
const flatRate = (cents) => () => cents;
const perKg = (centsPerKg) => (order) => order.weightKg * centsPerKg;
const freeOver = (threshold, fallback) => (order) => (order.subtotal >= threshold ? 0 : fallback(order));
const strategies = {
standard: freeOver(100, perKg(150)),
parcelShop: flatRate(299),
};
const small = { subtotal: 40, weightKg: 4 };
const large = { subtotal: 120, weightKg: 4 };
console.log(strategies.standard(small), strategies.standard(large), strategies.parcelShop(small));600 0 299The builders compose: freeOver wraps another strategy, so rules combine without a class for each combination. This is the decorator idea applied to strategies.
Class strategies for state and identity
When a strategy has several methods, or keeps state between calls, or needs a name and a description, a class is clearer.
class RetryPolicy {
delayFor() {
throw new Error("not implemented");
}
}
class FixedDelay extends RetryPolicy {
constructor(ms) {
super();
this.ms = ms;
}
delayFor() {
return this.ms;
}
}
class ExponentialBackoff extends RetryPolicy {
constructor(baseMs, maxMs) {
super();
this.baseMs = baseMs;
this.maxMs = maxMs;
}
delayFor(attempt) {
return Math.min(this.baseMs * 2 ** (attempt - 1), this.maxMs);
}
}
function delays(policy, attempts) {
return Array.from({ length: attempts }, (_, i) => policy.delayFor(i + 1));
}
console.log(delays(new FixedDelay(500), 4));
console.log(delays(new ExponentialBackoff(100, 1000), 6));[ 500, 500, 500, 500 ]
[ 100, 200, 400, 800, 1000, 1000 ]The client code, delays, asks for a delay and never checks the kind. A new policy, such as exponential backoff with jitter, is a new class. Jitter would use a random number, so an injected random source keeps the policy testable.
Sorting is the strategy you already use
const people = [
{ name: "Grace", age: 36 },
{ name: "Ada", age: 36 },
{ name: "Alan", age: 41 },
];
const byAge = (a, b) => a.age - b.age;
const byName = (a, b) => a.name.localeCompare(b.name);
const thenBy = (...comparators) => (a, b) => {
for (const compare of comparators) {
const result = compare(a, b);
if (result !== 0) return result;
}
return 0;
};
console.log(people.toSorted(byAge).map((p) => p.name));
console.log(people.toSorted(byName).map((p) => p.name));
console.log(people.toSorted(thenBy(byAge, byName)).map((p) => p.name));[ 'Grace', 'Ada', 'Alan' ]
[ 'Ada', 'Alan', 'Grace' ]
[ 'Ada', 'Grace', 'Alan' ]toSorted keeps the same algorithm and varies only the comparison. The first result shows Grace before Ada because both are 36 and the sort is stable, so ties keep their original order. thenBy is a strategy built from strategies. The same idea appears in Array.prototype.map, filter and reduce, which take the behavior as an argument.
In TypeScript
Types make the contract explicit and let the compiler check each strategy.
type ShippingStrategy = (order: { weightKg: number; subtotal: number }) => number;
const strategies = {
standard: (o) => o.weightKg * 1.5,
express: (o) => 10 + o.weightKg * 3,
} satisfies Record<string, ShippingStrategy>;
type Method = keyof typeof strategies;
function cost(method: Method, order: { weightKg: number; subtotal: number }): number {
return strategies[method](order);
}
console.log(cost("express", { weightKg: 2, subtotal: 30 }));
// cost("drone", { weightKg: 2, subtotal: 30 }); // error TS2345: Argument of type '"drone"' is not assignable to parameter of type 'Method'.16satisfies checks that every entry matches the strategy type while keeping the precise keys, so Method is exactly "standard" | "express", and a misspelled method is a compile error.
Strategy, state and factory
Three patterns share a shape: an object delegates to another object behind an interface. They differ in who picks and why.
| Pattern | Who chooses | When it changes | Purpose |
|---|---|---|---|
| Strategy | The caller or configuration | Rarely, by choice | Swap one algorithm |
| State | The object itself | Often, as it runs | Behavior by current mode |
| Factory | A creator function | At creation | Decide which object to build |
If the delegate swaps itself in response to events, it is the state pattern. If the caller picks it once, it is a strategy.
Testing
Strategies are the easiest code to test: each is a pure function with inputs and outputs. The context is tested with a trivial fake strategy, such as () => 7, which proves it uses whatever it is given. Test each real strategy on its own, including boundary cases.
import assert from "node:assert/strict";
import { test } from "node:test";
const checkoutTotal = (order, strategy) => order.subtotal + strategy(order);
const freeOver = (threshold, fallback) => (order) => (order.subtotal >= threshold ? 0 : fallback(order));
test("the context adds whatever the strategy returns", () => {
assert.equal(checkoutTotal({ subtotal: 10 }, () => 7), 17);
});
test("free shipping starts exactly at the threshold", () => {
const strategy = freeOver(100, () => 5);
assert.equal(strategy({ subtotal: 99 }), 5);
assert.equal(strategy({ subtotal: 100 }), 0);
});✔ the context adds whatever the strategy returns (0.8ms)
✔ free shipping starts exactly at the threshold (0.2ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0Pitfalls
Over-engineering. If there are two algorithms and they will not grow, an if is fine. Use a strategy when new variants are expected or when the branches are large.
Leaky interfaces. Strategies that need different inputs, such as one using weight and another using distance, push the context to pass everything, or to know which strategy it holds. Pass a full context object, or reconsider the split.
Lookup with untrusted keys, as shown above, and silent fallbacks: an unknown name should fail loudly with the list of valid names, not default to some strategy quietly.
Choosing in too many places. If five call sites each pick a strategy with their own condition, the decision is duplicated. Centralize the choice in one function.
Where the advice stops
Do not build a strategy hierarchy when passing a function says it all. And do not call every switch replacement a strategy: if the cases are not interchangeable behind one contract, the switch is honest. The pattern earns its place where several algorithms do the same job in different ways and the caller should be able to choose.
Choosing a strategy from data
In real applications the strategy often comes from outside the code, such as a customer's plan, a feature flag or a header on a request. Resolve the choice once, near the edge, into a strategy value, and pass that value inward. Business code deeper in the system then receives a function or object and never sees the plan name. This keeps conditionals about plans in one place, makes the core easy to test with simple fakes and lets you introduce a new plan by registering one more strategy and changing a configuration, with no edits to the logic that uses it.


