How to use the switch statement in JavaScript with logical expressions?

The switch statement in JavaScript is usually used as a way of performing different operations depending on the value of an expression. In the usual case, you specify it in the following way:

var number = 1;

switch (number) {
    case 1:
        console.log("One");
        break;
    case 2:
        console.log("Two");
        break;
    case 3:
        console.log("Three");
        break;
    default:
        console.log("Something else");
}

You can see that you provide the expression in parenthesis after the switch keyword and then the different values after the case keyword.

By only seeing this structure, it might not be obvious how to convert the following code to use a switch statement:

var number = 16;

if (number >= 1 && number <= 5) {
    console.log('Between 1 and 5.');
} else if(number >= 6 && number <= 10) {
    console.log('Between 6 and 10.');
} else if (number >= 11 && number <= 15) {
    console.log('Between 11 and 15.');
} else {
    console.log('Some other number.');
}

The situation is not easy because you are doing different things based on number ranges and not based on single values. One option would be to add a bunch of cases to the switch like this:

var number = 16;

switch (number) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        console.log('Between 1 and 5.');
        break;
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
        console.log('Between 6 and 10.');
        break;
    case 11:
    case 12:
    case 13:
    case 14:
    case 15:
        console.log('Between 11 and 15.');
        break;
    default:
        console.log('Some other number.');
}

This can result in a very long code if there are larger numbers at play. Luckily, we have a nice trick which can be used to simplify this:

var number = 55;

switch (true) {
    case number >= 1 && number <= 5:
        console.log('Between 1 and 5.');
        break;
    case number >= 6 && number <= 10:
        console.log('Between 6 and 10.');
        break;
    case number >= 11 && number <= 15:
        console.log('Between 11 and 15.');
        break;
    default:
        console.log('Some other number.');
}

As you can see, we are putting true into the switch parenthesis so a case will match if it evaluates to true. So it is doing the same as the if statement. Some people better like this syntax, some people not. It’s your choice which one you use, although the use of if is more widespread.