Overview of the Switch Statement
The switch statement is a control structure available in almost every programming and scripting language. It allows the developer to execute different blocks of code based on the value of an expression. It is often used as a cleaner alternative to multiple if-else statements. You may be asking yourself why use the switch statement since we already have if-else.
There are differences though. And depending on the task-at-hand, the switch statement can be a better alternative than if-else.
Structure:
switch (expression) {
case value1:
// execute this code block only
break;
case value2:
// execute this code block only
break;
default:
// execute if no cases match
}
A switch statement evaluates an expression and executes the code block for the first case that matches its value.
The break keyword is crucial. When encountered, it exits the entire switch statement immediately. Without it, execution will "fall through" and run the code in the subsequent case, even if the value doesn't match. If no matching case is found, the optional default block is executed.
Example:
let day = 'Monday';
let output = '';
switch (day) {
case 'Monday':
output = `Day is Monday`;
case 'Tuesday':
output = `Day is Tuesday`;
break;
case 'Wednesday':
output = `Day is Wednesday`;
break;
case 'Thursday':
output = `Day is Thursday`;
break;
case 'Friday':
output = `Day is Friday`;
break;
case 'Saturday':
output = `Day is Saturday`;
break;
case 'Sunday':
output = `Day is Sunday`;
break;
default:
output = `No day specified`;
}
// Output if day == 'Monday' OR day == 'Tuesday':
// Day is Tuesday
// Output if day == 'Saturday':
// Day is Saturday
// Output if day == 'Nothing'
// No day specified
This example demonstrates a crucial concept in JavaScript's switch statement: fallthrough. When day is 'Monday', the output will indeed be "Day is Tuesday". Here’s why: The switch statement finds a match on case 'Monday' and begins executing the code on the next line, setting output = 'Day is Monday'.
Because there is no break keyword at the end of the 'Monday' case, the logic "falls through" and continues to execute the very next line of code, which is the start of the 'Tuesday' case. It then executes output = 'Day is Tuesday', overwriting the previous value. Finally, the break keyword at the end of the 'Tuesday' case is encountered, which halts the execution of the switch block entirely.
The break statement is not optional for most use cases. It is essential for exiting the switch block once a specific case's code has finished running. Without it, execution will continue into the next case, whether it matches or not.
The default case is only executed if no other case values match the expression. It will not be executed simply because of a fallthrough from a matched case (unless that fallthrough leads all the way to it).