ECMAScript switch Statement

switch statement

The switch statement is a sibling of the if statement.

Developers can use the switch statement to provide a series of cases for an expression.

Syntax of the switch statement:

switch (equals)
  case when: statement;
    break;
  case when: statement;
    break;
  case when: statement;
    break;
  case when: statement;
    break;
...
  case when: statement;
    break;
  default: statement;

Each case represents 'if'. equals value whenexecutes statement

The keyword break causes the code to exit the switch statement. If the keyword break is not used, the code execution will continue into the next case.

The keyword default specifies the action to be taken when the result of the expression does not match any of the cases (in fact, it is relative to the else clause).

The switch statement is mainly used to avoid developers from writing the following code:

if (i == 20)
  alert("20");
else if (i == 30)
  alert("30");
else if (i == 40)
  alert("40");
else
  alert("other");

An equivalent switch statement would be like this:

switch (i) {
  case 20: alert("20");
    break;
  case 30: alert("30");
    break;
  case 40: alert("40");
    break;
  default: alert("other");
}

Switch statements in ECMAScript and Java

There are two differences between the switch statements in ECMAScript and Java. In ECMAScript, the switch statement can be used for strings, and it can specify cases with values that are not constants:

var BLUE = "blue", RED = "red", GREEN = "green";
switch (sColor) {
  case BLUE: alert("Blue");
    break;
  case RED: alert("Red");
    break;
  case GREEN: alert("Green");
    break;
  default: alert("Other");
}

Here, the switch statement is used for the string sColor, declaring cases with the variables BLUE, RED, and GREEN, which are completely valid in ECMAScript.