Understanding the Strategy Pattern in JavaScript
This article explains the Strategy design pattern, demonstrates its implementation in JavaScript through three code versions, discusses the drawbacks of naïve if‑else approaches, and outlines the pattern's advantages and disadvantages for creating flexible, maintainable code.
From a personal perspective, design patterns are hidden in everyday code; the article introduces the Strategy pattern as a practical example for daily project development.
Definition of the Strategy Pattern
The pattern is defined as "defining a family of algorithms, encapsulating each one, and making them interchangeable," essentially offering multiple choices and selecting one at runtime, analogous to using if and elseif statements.
Example
To calculate employee salaries, three levels are defined: senior (25 ¥/hour), mid (20 ¥/hour), junior (15 ¥/hour), assuming a 10‑hour workday.
First Implementation (if‑else)
const calculateSalary = function (workerLevel, workHours = 10) {
if (workerLevel === 'high') {
return workHours * 25
}
if (workerLevel === 'middle') {
return workHours * 20
}
if (workerLevel === 'low') {
return workHours * 15
}
}
console.log(calculateSalary('high')) // 250
console.log(calculateSalary('middle')) // 200Drawbacks of this version include a bulky function with many if‑else branches, violation of the Open‑Closed Principle when adding new levels, and poor reusability.
Second Implementation (Function Composition)
const workerLevelHigh = function (workHours) {
return workHours * 25
}
const workerLevelMiddle = function (workHours) {
return workHours * 20
}
const workerLevelLow = function (workHours) {
return workHours * 15
}
const calculateSalary = function (workerLevel, workHours = 10) {
if (workerLevel === 'high') {
return workerLevelHigh(workHours)
}
if (workerLevel === 'middle') {
return workerLevelMiddle(workHours)
}
if (workerLevel === 'low') {
return workerLevelLow(workHours)
}
}
console.log(calculateSalary('high', 10)) // 250
console.log(calculateSalary('middle', 10)) // 200While this improves reusability, the main function remains large and inflexible.
Third Implementation (Strategy Pattern)
The invariant part is the way the algorithm is invoked; the variable part is the algorithm itself. Using a JavaScript object as a key‑value map replaces the if‑else chain.
const strategies = {
"high": function (workHours) {
return workHours * 25
},
"middle": function (workHours) {
return workHours * 20
},
"low": function (workHours) {
return workHours * 15
},
}
const calculateSalary = function (workerLevel, workHours) {
return strategies[workerLevel](workHours)
}
console.log(calculateSalary('high', 10)) // 250
console.log(calculateSalary('middle', 10)) // 200Pros and Cons of the Strategy Pattern
Advantages
Reduces code complexity by eliminating numerous if‑else statements, helping tools like ESLint’s cyclomatic complexity rule.
Easy to switch, understand, and extend; adding a new level only requires updating the strategies object.
High reusability; strategies can be exported and used elsewhere in the system.
Disadvantages
Increases the learning curve for newcomers who must understand separate strategy objects or classes, potentially making the code harder to grasp than simple if‑else.
Conclusion
The Strategy pattern is widely applicable in business code to replace bulky conditional logic, making projects easier to maintain and extend; the author finds it very useful in practice.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
