Understanding Switch Statements in JavaScript

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

switch(<expression>) {
  case <condition1>:
    . . . // Execute if <condition1> is matched.
    break;
  case <condition2>:
    . . . // Execute if <condition2> is matched.
    break;
  default:
    . . . // Execute if no conditions are matched.
}

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.

let weather = "snowy";

switch (weather) {
  case "sunny":
    console.log("the weather is sunny");
    break;
  case "cloudy":
    console.log("the weather is cloudy");
    break;
  default:
    console.log("unknown weather");
}
unknown 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.

let weather = "sunny";

switch (weather) {
  case "sunny":
    console.log("the weather is sunny");
  case "cloudy":
    console.log("the weather is cloudy");
  default:
    console.log("unknown weather");
}
the weather is sunny
the weather is cloudy
unknown 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.

let temperature = "10";

switch (temperature) {
  case 10:
    console.log("temperature is at 10 degrees");
    break;
  case 20:
    console.log("temperature is at 20 degrees");
    break;
  default:
    console.log("unknown temperature");
}
unknown 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.