Understanding Switch Statements in JavaScript

Another flow control technique similar to the if statement is the switch statement, which has the following syntax:

javascript
1switch(<expression>) {
2  case <condition1>:
3    . . . // Execute if <condition1> is matched.
4    break;
5  case <condition2>:
6    . . . // Execute if <condition2> is matched.
7    break;
8  default:
9    . . . // Execute if no conditions are matched.
10}

The <expression> will be evaluated once, and the result will be compared to each condition, which are defined by the case keyword.

If the condition is matched, the corresponding code block will be executed. After that, the break keyword will break JavaScript out of the switch block.

And if no conditions are matched, the default block will be executed instead.

javascript
1let weather = "snowy";
2
3switch (weather) {
4  case "sunny":
5    console.log("the weather is sunny");
6    break;
7  case "cloudy":
8    console.log("the weather is cloudy");
9    break;
10  default:
11    console.log("unknown weather");
12}
text
1unknown weather

It is important to note that the break keyword should not be omitted. If you do, JavaScript will keep executing the next case, even if the condition does not match.

javascript
1let weather = "sunny";
2
3switch (weather) {
4  case "sunny":
5    console.log("the weather is sunny");
6  case "cloudy":
7    console.log("the weather is cloudy");
8  default:
9    console.log("unknown weather");
10}
text
1the weather is sunny
2the weather is cloudy
3unknown weather

Also, notice that when JavaScript matches the expression result to conditions, it uses === (equal value and equal type) instead of ==. For example, in the following case, JavaScript will not match any conditions, and the default block will be executed.

javascript
1let temperature = "10";
2
3switch (temperature) {
4  case 10:
5    console.log("temperature is at 10 degrees");
6    break;
7  case 20:
8    console.log("temperature is at 20 degrees");
9    break;
10  default:
11    console.log("unknown temperature");
12}
text
1unknown temperature

This is because the variable temperature is defined as the string "10", but the switch statement is trying to compare it to the number 10.

Compared to the if else statement, switch has limited functionality, as the comparisons are strictly equal value and equal type (===), and the syntax is somewhat awkward, such as the break keyword that cannot be omitted. In practice, it might be a good idea to use if else, as it is easier to read.

However, if you have a large number of conditions and want better performance, you should go with switch. For JavaScript, the if else statements will be processed line by line, but a switch statement will be compiled into a branch table, which provides faster execution.