DevPath · Learn to code ESPTEN

Design patterns

Strategy pattern

Strategy pattern

The strategy pattern defines a family of interchangeable algorithms and lets you choose which one to use at runtime. In JavaScript, since functions are values, it is implemented very naturally by storing functions in an object.

const strategies = {
  normal: (price) => price,
  member: (price) => price * 0.9,    // 10% discount
  vip: (price) => price * 0.8,       // 20% discount
};

function calculatePrice(price, customerType) {
  const strategy = strategies[customerType] || strategies.normal;
  return strategy(price);
}

console.log(calculatePrice(100, "vip"));    // 80
console.log(calculatePrice(100, "member")); // 90

Why is it useful?

Examples

Strategy to sort in different ways

const sorters = {
  asc: (a, b) => a - b,
  desc: (a, b) => b - a,
};
const numbers = [3, 1, 2];
console.log([...numbers].sort(sorters.asc));
console.log([...numbers].sort(sorters.desc));
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Singleton and observerView the module →