Javascript switch case

Learn how to do logical conditioning with switch case in javascript.

switch statement executes the code associated with the matching case. To match the case it evaluates an expression. If there are multiple match cases then the first case will be evaluated.

Syntax

switch(expression) {
  case x:
    // code to execute when case x is matched.
    // code block
    break;
  case y:
    // code to execute when case y is matched. 
    // code block
    break;
  default:
    // code to execute when there is no match.
    // code block
}

expression

Required. An expression whose result needs to be matched.

case

Optional. Different cases with associated code block to be executed.

default

Optional. Statement to be executed when there is no match.

break

Optional(For each case including default). To break the execution.

Example

let mood = "";

switch (1 + 1) {
  case 0:
    mood = "Happy";
    break;
  case 1:
    mood = "Sad";
    break;
  case 2:
     mood = "Laughing";
    break;
  case 3:
    mood = "Crying";
}

console.log(mood);
//Laughing

How switch works in javascript.

  • The expression inside the switch is evaluated only once.
  • Then the value of expression is matched with the listed cases.
  • It use strict equality === for matching.
  • If there is a match then code of the associated case will be evaluated.
  • If there is no match then default case will be evaluated (if provided).

Default case

let mood = "";

switch (21 / 3) {
  case 0:
    mood = "Happy";
    break;
  case 1:
    mood = "Sad";
    break;
  case 2:
     mood = "Laughing";
    break;
  case 3:
    mood = "Crying";
    break;
  default:
    mood = 'Angry';
    break;
}

console.log(mood);
//Angry

You can skip the break statement if you want. Also default does not have to be at last it can be placed any where.

let mood = "";

switch (21 / 3) {
  default:
    mood = 'Angry';
    break;
  case 0:
    mood = "Happy";
    break;
  case 1:
    mood = "Sad";
    break;
  case 2:
     mood = "Laughing";
    break;
  case 3:
    mood = "Crying";
    break;
}

console.log(mood);
//Angry

You can also share the same code block with multiple cases.

let mood = "";

switch (1 + 1) {
  default:
    mood = 'Angry';
    break;
  case 0:
  case 1:
    mood = "Sad";
    break;
  case 2:
  case 3:
    mood = "Crying";
    break;
}

console.log(mood);
//Crying

In the above example case 0: and case 1: & case 2: and case 3: share the same code block.

You can also do the logical conditioning with if else.