Improving JavaScript Conditional Logic: Short‑Circuit, Ternary, Switch, and Strategy Pattern
This article explains how to replace verbose nested if‑else statements in JavaScript with short‑circuit evaluation, ternary operators, switch‑case constructs, and object‑based strategy patterns, providing clearer, more maintainable code through concise examples and practical use‑cases.
Many developers encounter deeply nested if else structures that become hard to read and maintain; the article starts by acknowledging the pain points of such code.
It introduces JavaScript's logical OR short‑circuit ( || ) as a way to simplify a simple conditional assignment, showing the transformation from a multi‑line if else block to a single line: let c = a || b;
The ternary operator ( condition ? expr1 : expr2 ) is presented next, with a side‑by‑side comparison of an if else function and its ternary equivalent, illustrating how one‑line expressions can replace simple branches.
For scenarios with multiple distinct branches, the article demonstrates the switch case statement, providing a full example that maps four input types (A, B, C, D) to numeric outputs, and contrasts it with an equivalent series of if else if statements.
To further improve scalability, the concept of object configuration (or strategy pattern) is introduced. Several code snippets show how a plain object or a Map can replace repetitive if else logic for discount calculation, and how the same pattern can be extended to calculate year‑end bonuses, even handling additional dimensions such as department multipliers.
The article concludes by emphasizing that while if else is not discouraged, developers should consider these alternatives to enhance readability, maintainability, and extensibility of their JavaScript code.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.