Switch Statements
JavaScript Switch Statements
Switch statements in JavaScript are a type of conditional statement that allow you to check the value of an expression and perform different actions based on different cases.
Syntax
The basic syntax of a switch statement is as follows:
switch (expression) { case value1: // code block to be executed if expression matches value1 break; case value2: // code block to be executed if expression matches value2 break; ... default: // code block to be executed if expression doesn't match any of the cases }
In a switch statement, the `expression` is evaluated once, and its value is compared with the values of each `case`. If there is a match, the corresponding code block is executed until a `break` statement is encountered or until the end of the switch statement. If no match is found, the code block under the `default` case (if present) will be executed.
Example
Here's an example that demonstrates how to use a switch statement:
let day = new Date().getDay(); let dayName; switch (day) { case 0: dayName = "Sunday"; break; case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; case 6: dayName = "Saturday"; break; default: dayName = "Unknown"; } console.log("Today is " + dayName);
In this example, the switch statement checks the value of `day` and assigns the corresponding day name to the variable `dayName`. The `dayName` variable is then printed to the console.
Multiple Cases
You can also have multiple cases that share the same code block. To do this, simply omit the `break` statement for the matching cases:
let fruit = "apple"; let season; switch (fruit) { case "apple": case "pear": case "plum": season = "Autumn"; break; case "banana": case "mango": season = "Summer"; break; case "orange": case "grapefruit": season = "Winter"; break; default: season = "Unknown"; } console.log("The season of the fruit is " + season);
In this example, the switch statement checks the value of `fruit` and assigns the corresponding season to the variable `season`. The cases for "apple", "pear", and "plum" share the same code block and will result in the season being set to "Autumn".
Key Takeaways
- Switch statements allow you to check the value of an expression and perform different actions based on different cases.
- The `expression` is evaluated once, and its value is compared with the values of each `case`.
- Each case block should end with a `break` statement to prevent fall-through to the next case.
- You can have multiple cases that share the same code block by omitting the `break` statement for those cases.
- The `default` case is optional and is executed if the expression doesn't match any of the cases.
Comments
Post a Comment