
if-else vs switch
if-else vs switch 관련
As the number of judgment conditions increases, it becomes more preferable to use switch instead of if-else.
if (color == 'blue') {
} else if (color == 'yellow') {
} else if (color == 'white') {
} else if (color == 'black') {
} else if (color == 'green') {
} else if (color == 'orange') {
} else if (color == 'pink') {
}
switch (color) {
case 'blue': break
case 'yellow': break
case 'white': break
case 'black': break
case 'green': break
case 'orange': break
case 'pink': break
}
In situations like the one above, from a readability perspective, using switch is better (JavaScript's switch statement is not based on hash implementation but on loop judgment, so from a performance perspective, if-else and switch are the same).
Why switch
is better for multiple conditions:
1. Improved readability
Switch statements present a clearer visual structure when dealing with multiple conditions against the same variable. The case statements create a more organized, tabular format that's easier to scan and understand.
2. Cleaner code maintenance
Adding or removing conditions in a switch statement is simpler and less error-prone. With if-else chains, it's easy to accidentally break the chain or forget an "else" keyword.
3. Less repetition
In the if-else example, we repeat checking the same variable (color
) multiple times, while in switch we specify it once at the top.
4. Better for debugging
When debugging, it's easier to set breakpoints on specific cases in a switch statement than trying to identify which part of a long if-else chain you need to target.
5. Intent signaling
Using switch communicates to other developers that you're checking multiple possible values of the same variable, rather than potentially unrelated conditions.
For modern JavaScript, there's another alternative worth considering for simple value mapping – object literals:
const colorActions = {
'blue': () => { /* blue action */ },
'yellow': () => { /* yellow action */ },
'white': () => { /* white action */ },
'black': () => { /* black action */ },
'green': () => { /* green action */ },
'orange': () => { /* orange action */ },
'pink': () => { /* pink action */ }
};
// Execute the action if it exists
if (colorActions[color]) {
colorActions[color]();
}
This approach provides even better performance (O(1) lookup time) compared to both if-else and switch statement approaches.