What is the purpose of the `switch` statement?
TL;DR
The switch statement is used to execute one block of code among many based on the value of an expression. It is an alternative to using multiple if...else if statements. The switch statement evaluates an expression, matches the expression's value to a case label, and executes the associated block of code. If no case matches, the default block is executed.
switch (expression) {case value1:// code to be executed if expression === value1break;case value2:// code to be executed if expression === value2break;default:// code to be executed if no case matches}
Purpose of the switch statement
Simplifies multiple conditional checks
The switch statement provides a cleaner and more readable way to handle multiple conditional checks compared to using multiple if...else if statements. It is particularly useful when you need to compare the same expression against different values.
Syntax and structure
The basic syntax of a switch statement is as follows:
switch (expression) {case value1:// code to be executed if expression === value1break;case value2:// code to be executed if expression === value2break;// more cases...default:// code to be executed if no case matches}
How it works
- Expression evaluation: The
switchstatement evaluates the expression once. - Case matching: It compares the result of the expression to the values of each
caselabel. - Code execution: If a match is found, the code associated with that
caseis executed. - Break statement: The
breakstatement is used to exit theswitchblock. If omitted, the nextcasewill be executed (fall-through behavior). - Default case: The
defaultcase is optional and executes if no matchingcaseis found.
Example
Here is an example of a switch statement in action:
let fruit = 'apple';switch (fruit) {case 'banana':console.log('Banana is yellow.');break;case 'apple':console.log('Apple is red.');break;case 'grape':console.log('Grape is purple.');break;default:console.log('Unknown fruit.');}
In this example, the output will be Apple is red. because the value of fruit matches the case 'apple'.
Fall-through behavior
If the break statement is omitted, the switch statement will continue to execute the subsequent case blocks until it encounters a break or the end of the switch block. This is known as fall-through behavior.
let day = 2;switch (day) {case 1:console.log('Monday');case 2:console.log('Tuesday');case 3:console.log('Wednesday');default:console.log('Unknown day');}
In this example, the output will be:
TuesdayWednesdayUnknown day
This happens because there are no break statements to stop the execution after the case 2 block.