JavaScript Switch

The switch statement is used to perform different actions based on different conditions.

The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if statement that we have learned in previous page. But it is convenient than if..else..if because it can be used with numbers, characters etc.

The syntax

The switch has one or more case blocks and an optional default.

switch(x) { case 'value1': // if (x === 'value1') ... [break] case 'value2': // if (x === 'value2') ... [break] default: ... [break] }

The JavaScript Switch Statement

Use the switch statement to select one of many code blocks to be executed.

switch(expression) {
  case x:
    // code block
  case y:
    // code block
    // code block

This is how it works:

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • If there is no match, the default code block is executed.

Example -