JS switch

Last Updated: March 16, 2022

JS switch allows you to write several if-else statements easily.

Javascript switch statement

One of the many code blocks will be selected based on the conditions.

Syntax JS switch

code block will be executed based on the condition

switch(expression) {
  case a:
    // code block
    break;
  case b:
    // code block
    break;
  default:
    // code block
} 

Example

Get the day of the week as a string

var dd = 4;

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