JavaScript : Switch Statement

In JavaScript, the switch statement provides a way to execute different blocks of code based on the value of an expression. It's an alternative to using multiple if , else if , and else statements when you have multiple conditions to check against a single value. Here's how the switch statement works:

Syntax:


switch (expression) {
  case value1:
    // Code block to execute if expression equals value1
    break;
  case value2:
    // Code block to execute if expression equals value2
    break;
  case value3:
    // Code block to execute if expression equals value3
    break;
  default:
    // Code block to execute if expression does not match any case
}

 

  • The expression is evaluated once and compared with the values associated with each case .
  • If a case matches the expression , the corresponding block of code is executed.
  • The break statement is used to exit the switch statement once a match is found. If omitted, the next case will be executed regardless of whether its value matches the expression.
  • If no case matches the expression , the default block is executed.

Example:


let day = new Date().getDay();
let dayOfWeek;

switch (day) {
  case 0:
    dayOfWeek = "Sunday";
    break;
  case 1:
    dayOfWeek = "Monday";
    break;
  case 2:
    dayOfWeek = "Tuesday";
    break;
  case 3:
    dayOfWeek = "Wednesday";
    break;
  case 4:
    dayOfWeek = "Thursday";
    break;
  case 5:
    dayOfWeek = "Friday";
    break;
  case 6:
    dayOfWeek = "Saturday";
    break;
  default:
    dayOfWeek = "Invalid day";
}

console.log("Today is " + dayOfWeek);
 

Multiple Cases:


You can group multiple cases together to execute the same code block for different values.


let month = new Date().getMonth();
let season;

switch (month) {
  case 11:
  case 0:
  case 1:
    season = "Winter";
    break;
  case 2:
  case 3:
  case 4:
    season = "Spring";
    break;
  case 5:
  case 6:
  case 7:
    season = "Summer";
    break;
  case 8:
  case 9:
  case 10:
    season = "Autumn";
    break;
  default:
    season = "Invalid month";
}

console.log("The current season is " + season);
 

The switch statement provides a concise way to handle multiple conditions based on the value of an expression. It's particularly useful when you have a large number of conditions to evaluate.