JavaScript switch...case Statement

The JavaScript switch...case statement executes different blocks of code based on the value of a given expression.

Here's a simple example of the switch...case statement. You can read the rest of the tutorial for more.

Example

let trafficLight = "green";
let message = ""
 
switch (trafficLight) {
    case "red":
        message = "Stop immediately.";
        break;
    case "yellow":
        message = "Prepare to stop.";
        break;
    case "green":
        message = "Proceed or continue driving.";
        break;
    default:
        message = "Invalid traffic light color.";
}
 
console.log(message)
 
// Output: Proceed or continue driving.

The above program checks the value of trafficLight and prints the corresponding meaning of the traffic light. If the value doesn't match any of the specified cases, it prints Invalid traffic light color.


Syntax of the switch...case Statement

switch (expression) {

    case value1:
        // code block to be executed
        // if expression matches value1
        break;

    case value2:
        // code block to be executed
        // if expression matches value2
        break;

    ...

    default:
        // code block to be executed
        // if expression doesn't match any case
}

Here,

  1. The switch