Expressions in the Case Label

The switch Statement

Expressions in the Case Label

🙋 Need help? Ask an expert now!

The expression in the case label can be anything, a number, a boolean, a string, etc. It is extremely useful when you need to check the value of the variable against many different possibilities. However, if you only have 1-3 cases, it might be better for you to just use an if-else statement to simplify the process. The cases are evaluated from top to bottom, and the break; statement exits the switch statement when it is called.

The example above uses "true" instead of a value of a variable in the expression. Therefore, the expressions inside the case label that evaluate to true are executed when the switch statement is executed. In this case, since the expression twenties > 21 && twenties < 24 evaluates to true, the statements under the case are executed before the break; statement is called. Play around with the value of the variable age and print different statements to the console.

Edit Me on GitHub!

Application Question

Consider the following code segment:

let total = 20;
switch (true){
    case (total / 2 == 10 && total > 10): console.log(1); break;
    case (total != 20): console.log(2); break;
    case (total / 2 == 40 || total > 10): console.log(3); break;
    case (total + 20 == 40 && total != 20): console.log(4); break;
    case (total == 20 && total % 2 == 0): console.log(5); break;
}

What will the following code print to the console?