Table of Contents
Switch Statement in Java Script
In JavaScript, a switch statement is a control flow statement that allows a program to evaluate an expression and choose from multiple possible code blocks to execute based on the value of that expression. It provides a more concise way to write multiple if…else if…else statements.
Here’s the syntax for a switch statement:
javascript
switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
// additional cases as needed
default:
// code to be executed if none of the cases match
}
- expression: The value that is being compared in each case.
- case valueX: A specific value that expression is compared against.
- break: A keyword that terminates the switch statement. If omitted, the execution will continue to the next case regardless of whether the condition is met.
Here’s an example of a switch statement in JavaScript:
switch (day) {
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;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName); // Output: Wednesday
In this example, the switch statement checks the value of the day variable and assigns the corresponding day name to the dayName variable. If day is 3, the output will be “Wednesday.” If day doesn’t match any of the specified cases, the default case will be executed, assigning “Invalid day” to dayName.