DEV Community

roadpilot
roadpilot

Posted on

Something you may not know about the Javascript "Switch" statement...

The switch statement is used to perform different actions based on different conditions. You use the switch statement to select one of many code blocks to be executed. The following "if then" statement, where x could be any value but will only give a result with 0 or 1:

if (x===0) {
    text = "Zero";
} else if (x===1) {
    text = "One";
} else {
    text = "No value found";
}
Enter fullscreen mode Exit fullscreen mode

...can be re-written as this "switch" statement:

switch (x) {
  case 0:
    text = "Zero";
    break;
  case 1:
    text = "One";
    break;
  default:
    text = "No value found";
}
Enter fullscreen mode Exit fullscreen mode

TIP: You always need to include the "break" command if you want the switch to stop when it finds a match.

One thing to keep in mind, Switch cases use strict comparison (===). The values must be of the same type to match. A strict comparison can only be true if the operands are of the same type.
In the above examples, "0" would not return a match but 0 would.

But what if you wanted to switch on something like this:

if (time < 10) {
  greeting = "Good morning";
} else if (time < 20) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}
Enter fullscreen mode Exit fullscreen mode

You might think you could do it like this:

switch(time){
    case (<10):
        greeting = "Good morning";
        break;
    case (<20):
        greeting = "Good day";
        break;
    default:
        greeting = "Good evening";
}
Enter fullscreen mode Exit fullscreen mode

But switch comparisons do not work that way. Switch follows these rules:

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case. (Since the values can not be compared, they can not match)
  • If there is a match, the associated block of code is executed.
  • If there is no match, the default code block is executed.

But here's one thing you can do. Since the value of the expression is compared to the values of each case, if you set the value of the expression to 'true', then you can make any case value an expression that would evaluate to true (or false) to test for a match. For example, we already know the above switch expression will not work. But if it were rewritten as follows:

switch(true){
    case (time < 10):
        greeting = "Good morning";
        break;
    case (time < 20):
        greeting = "Good day";
        break;
    default:
        greeting = "Good evening";
}

Enter fullscreen mode Exit fullscreen mode

...then you could use "switch" as alternative to the "if then" JavaScript statement.

The more you know!

Top comments (0)