In JavaScript, the switch statement is a control flow statement that allows you to perform different actions based on different conditions. It provides a concise way to write multiple if-else statements that compare a single value against multiple cases.
The syntax of a switch statement is as follows:
switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
// more cases...
default:
// code to be executed if none of the cases match
}
Here's a breakdown of how a switch statement works:
The expression is evaluated once and its value is compared against each case value.
If a case value matches the expression value, the corresponding block of code is executed until a break statement is encountered or the switch statement ends.
If no case value matches the expression value, the code block associated with the default label is executed (optional).
The break statement is used to exit the switch statement and prevent execution of the subsequent code blocks. If break is omitted, execution will continue to the next case (known as "falling through").
Here's an example of a switch statement that determines the day of the week based on a numeric input:
var day = 1;
var dayOfWeek;
switch (day) {
case 1:
dayOfWeek = "Sunday";
break;
case 2:
dayOfWeek = "Monday";
break;
case 3:
dayOfWeek = "Tuesday";
break;
case 4:
dayOfWeek = "Wednesday";
break;
case 5:
dayOfWeek = "Thursday";
break;
case 6:
dayOfWeek = "Friday";
break;
case 7:
dayOfWeek = "Saturday";
break;
default:
dayOfWeek = "Invalid day";
}
console.log(dayOfWeek); // Output: "Sunday"
In the example above, the switch statement compares the value of the day variable against each case value. Since day is 1, the case with the value 1 matches, and the corresponding block of code is executed, assigning the value "Sunday" to the dayOfWeek variable.
Switch statements are useful when you have multiple cases to evaluate against a single expression and can help improve the readability and maintainability of your code.