JavaScriptMedium
Explain the concept of the Strategy pattern
By FrontendPro Editorial Team Updated 8/8/2026
#JavaScript
Answer
The Strategy pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one as a separate class, and make them interchangeable. This pattern lets the algorithm vary independently from the clients that use it. For example, if you have different sorting algorithms, you can define each one as a strategy and switch between them without changing the client code.
js
class Context {
constructor(strategy) {
this.strategy = strategy;
}
executeStrategy(data) {
return this.strategy.doAlgorithm(data);
}
}
class ConcreteStrategyA {
doAlgorithm(data) {
// Implementation of algorithm A
return "Algorithm A was run on " + data;
}
}
class ConcreteStrategyB {
doAlgorithm(data) {
// Implementation of algorithm B
return "Algorithm B was run on " + data;
}
}
// Usage
const context = new Context(new ConcreteStrategyA());
context.executeStrategy("someData"); // Output: Algorithm A was run on someData
