Switch in JavaScript

Switch statements express conditionals across many branches.

Here’s a basic switch.

let i = 2;
console.log("Write " + i + " as ");
switch (i) {
    case 1:
        console.log("one");
        break;
    case 2:
        console.log("two");
        break;
    case 3:
        console.log("three");
        break;
}

You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.

let day = new Date().getDay();
switch (day) {
    case 6:
    case 0:
        console.log("It's the weekend");
        break;
    default:
        console.log("It's a weekday");
        break;
}

switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.

let hour = new Date().getHours();
switch (true) {
    case hour < 12:
        console.log("It's before noon");
        break;
    default:
        console.log("It's after noon");
        break;
}

A type switch compares types instead of values. You can use this to discover the type of a value in JavaScript. In this example, the type of the variable is logged.

function whatAmI(i) {
    switch (typeof i) {
        case "boolean":
            console.log("I'm a bool");
            break;
        case "number":
            console.log("I'm an int");
            break;
        default:
            console.log(`Don't know type ${typeof i}`);
            break;
    }
}

whatAmI(true);
whatAmI(1);
whatAmI("hey");

To run the code, copy it into an .js file and execute it using node.

$ node switch.js
Write 2 as 
two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string