In JavaScript, the switch statement is a control statement used to execute different code blocks based on different conditions. It is often used as a shorthand for an if-else statement with multiple branches.
Here's the basic syntax of a switch statement:
javascript
switch (expression) { case value1: // code block to execute if expression matches value1 break; case value2: // code block to execute if expression matches value2 break; // more cases can be added default: // code block to execute if none of the cases match expression }
Here's an example to demonstrate how to use the switch statement:
javascript
let dayOfWeek = 3; // Wednesday let dayName; switch (dayOfWeek) { 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 day"; } console.log(dayName); // Output: "Wednesday"
In the example above, the switch statement compares the value of dayOfWeek with the different cases, and when it finds a match, it executes the corresponding code block. If none of the cases match, the code inside the default block will be executed.
Note that the break statement is used to terminate the code block associated with each case. If you forget to add a break statement, the code will continue executing the next case's code block, even if it doesn't match the expression.


0 Comments