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:
weekendWithout 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 2Notes
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
- Conditional (ternary) operator — Picks one of two values by a condition — a short if...else.
- Strict equality (===) — Compares values without type conversion.
In the tutorial
- The switch statement — How to choose one of many options with switch in JavaScript — case, break, default and grouping cases.