JavaScript Switch-Case

In JavaScript, the switch statement can be used in place of the if...else statement to handle numerous potential situations based on the result of a single expression.

This is a basic syntax of the switch-case statement:

switch (expression)
 { case value1: // code to be executed if the expression is equal to value1 break;
 case value2: // code to be executed if the expression is equal to value2 break; // and so on... 
default: // code to be executed if none of the cases match the expression }

The expression of switch-case is evaluated once and the value of the expression is compared with each case value. If there is a match, the code block associated with that case is executed. The break statement is used to exit the switch block once a match is found.

This is an example of the switch-case statement:

let day = 2; 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 = "Invalid day"; } 
console.log(dayName);

In this example, the switch statement evaluates the value of the day variable and assigns the corresponding day name to the dayName variable. Since day is equal to 2, the code block associated with the case 2 statement is executed, and dayName is set to "Tuesday". The console.log() statement then prints "Tuesday" to the console.

Note that the default case is optional, and will be executed if none of the cases match the expression.

Last updated