Open In App

How to write a switch statement in JavaScript?

In JavaScript, a switch statement is a control flow statement that evaluates an expression and executes code based on matching cases. It provides a more concise and readable way to handle multiple possible conditions compared to nested if...else statements.

Syntax:

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;
// more cases can be added as needed
default:
// code block to be executed if expression does not match any case
}

Parameters:

Example: Here, the switch statement evaluates the value of the day variable. Depending on the value of day, the corresponding case is matched, and the associated code block is executed. If none of the cases match, the default case is executed. In this case, it day is "Monday", the message “Today is Monday.” will be logged to the console.




const day = "Monday";
 
switch (day) {
  case "Monday":
    console.log("Today is Monday.");
    break;
  case "Tuesday":
    console.log("Today is Tuesday.");
    break;
  case "Wednesday":
    console.log("Today is Wednesday.");
    break;
  case "Thursday":
    console.log("Today is Thursday.");
    break;
  case "Friday":
    console.log("Today is Friday.");
    break;
  default:
    console.log("It's a weekend day.");
}

Output
Today is Monday.


Article Tags :