JavaScript Tutorial JavaScript References

JavaScript - Switch



The Switch statement in JavaScript language is used to execute one of many code statements. It can be considered as group of If-else statements.

Syntax

switch (expression){
  case 1:
     statement 1;
     break;
  case 2:
     statement 2;
     break;
     ...
     ...
     ...
  case N:
     statement N;
     break;
  default:
     default statement;
} 

The switch expression is evaluated and matched with the cases. When the case matches, the following block of code is executed.

Flow Diagram:

JavaScript Switch

Example:

In the example below, the switch expression is a variable called day. The getDay() function is used to get the current day as a number. Based on the value of the day variable, the program prints the current day.

var day = new Date().getDay();
var txt;

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

txt = "Today is " + txt + ".";

The output (value of txt) after running above script will be:


default and break statements

Default case and break statement are optional here.

  • Default Case: Default Statement is executed when there is no match between switch expression and test cases.
  • Break Statement: Break statement is used to get out of the Switch statement after a match is found.

Example:

In the example below, default statement is used. The default code block is executed, whenever the value of switch expression day is not equal to 0 or 6.

var day = new Date().getDay();
var txt;

switch(day) {
  case 0: 
    txt = "Today is Sunday.";
    break; 
  case 6: 
    txt = "Today is Saturday.";
    break;
  default: 
    txt = "Today is not a weekend.";
}

The output of the above code will be:



Please note that, the default statement can be placed at any position in the switch statement. In such instances, add break statement with default statement.

Example:

Consider the example below, where default statement is placed on the top in a switch statement.

var day = new Date().getDay();
var txt;

switch(day) {
  default: 
    txt = "Today is not a weekend.";
    break;
  case 0: 
    txt = "Today is Sunday.";
    break; 
 case 6: 
    txt = "Today is Saturday.";
}

The output of the above code will be:


Common code blocks

There are instances where same code block is required in multiple cases.

Example:

In the example below, same code block is shared for different switch cases.

var day = new Date().getDay();
var txt;

switch(day) {
  case 1:
  case 2:
  case 3:
  case 4:
  case 5:
    txt = "Today is a weekday.";
    break;
  case 0:
  case 6: 
    txt = "Today is a weekend.";
}

The output of the above code will be: