Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

switch

Picks a branch of code by value.

Available since: ES3

Syntax

switch (value) { case a: … break; default: … }

Examples

Choosing by value:

const day = 'sat';
 
switch (day) {
  case 'sat':
  case 'sun':
    console.log('weekend');
    break;
  default:
    console.log('weekday');
}

Output:

weekend

Without break execution falls through:

const level = 1;
 
switch (level) {
  case 1:
    console.log('level 1');
  case 2:
    console.log('level 2');
    break;
  case 3:
    console.log('level 3');
}

Output:

level 1
level 2

Notes

Values are compared strictly, like ===: case '1' does not match the number 1. If you just map a value to a result, an object is shorter: const labels = { sat: 'weekend' }.

See also

In the tutorial

  • The switch statement — How to choose one of many options with switch in JavaScript — case, break, default and grouping cases.

Thanks for reading!

Donate to the site — we work hard for you.