The switch statement
When one value has to be compared with a long list of options, an else if chain gets bulky. For such cases there is the switch statement — it compares the value with each option in turn.
How switch works
The value being checked goes in parentheses after switch, and each option starts with the word case. The code of the option that matches the value runs:
const color = 'green';
switch (color) {
case 'red':
console.log('Stop');
break;
case 'green':
console.log('Go'); // Go
break;
}The word break ends the switch: after it the program continues with the code that follows the closing brace.
default
The default block runs if none of the options matched. It plays the role of else in a normal condition:
const status = 500;
switch (status) {
case 200:
console.log('OK');
break;
case 404:
console.log('Not found');
break;
default:
console.log('Unknown status'); // Unknown status
}default usually goes last, so it does not need a break.
Several options with the same code
If several values need the same code, write their options one after another and the code once, under the last one:
const day = 'Saturday';
switch (day) {
case 'Saturday':
case 'Sunday':
console.log('Day off'); // Day off
break;
default:
console.log('Working day');
}The empty case 'Saturday': has no code, so execution moves on to the next option.
Comparison is strict
switch compares values like the === operator — taking the type into account. The string '1' will not match the number 1:
const choice = '1';
switch (choice) {
case 1:
console.log('First item chosen');
break;
default:
console.log('Unknown choice'); // Unknown choice
}Form data arrives as strings, so convert it to a number with Number() first, or write the options as strings.
switch or if
switch is handy when one variable is checked for equality with specific values: a command code, a day of the week, an order status. It does not suit ranges like "over 90" — those need if with else if.
Common mistake
If you forget break, execution "falls through" into the next option, and its code runs too even though the value did not match:
const level = 'easy';
switch (level) {
case 'easy':
console.log('Easy level'); // Easy level
case 'hard':
console.log('Hard level'); // Hard level
}Make sure every option with code ends with break.