JavaScript switch Statement for multiple Cases

← PrevNext →

I knew how to do this. But, I couldn’t recollect when I needed this. So, I thought I should share a quick tip post on how to add multiple cases in a switch statement in JavaScript.

A switch statement executes a piece of code based of different cases or conditions. Its like the if…else statement. For example,

<script>
let show_sub = (str) => {
    switch (str) 
    {
        case 'Math':
            alert ('Math is interesting');
            break;
        case 'JS':
            alert ('I love to code');
            break;
    }
}

show_sub('Math');
</script>
Try it

It’s a simple switch case… statement example. I have only one case condition each. I am using the break keyword to break or come out of the condition if a statement is true.

Switch statement with Multiple cases

Now, I want to do multiple case tests, using the switch statement. Here’s how I can do this.

<script>
let schedule = (d) => {
    const day = d.getDay();
    switch (day) 
    {
        case 1: case 3: case 5:
            document.write ('Subjects: Math, History, Economics');
            break;
        case 2: case 4:
            document.write ('Subjects: Computers, Science, Physics');
            break;
    }
}

schedule(new Date());
</script>
Try it

I am using the fall-through feature in the above example. As you can see, a colon separates multiple cases (:). There is one “break” keyword for more than one condition. Not every case has any break point and it keeps looking for a match until it finds one.

Cases 1, 3 and 5 indicate days of a week like Monday, Wednesday and Friday. The values are number. If it’s a string, use double quotes or single quotes, like this.

<script>

let load_Python_Tutorials = () => {
    document.write ('Python by the Author...');
}

let load_MsExcel_Tutorials = () => {
    document.write ('Excel for all...');
}

let schedule = (sClass) => {
    switch (sClass) 
    {
        case 'XI': 
        case 'XII':
            load_Python_Tutorials();    // load python tutorials for classes XI and XII
            break;
        case 'VI': 
        case 'VII': 
        case 'VIII':
            load_MsExcel_Tutorials();   // load Ms-Excel tutorials for classes XI and XII
            break;
    }
}

schedule('XI');

</script>

Note: You can add multiple cases either vertically (see the above example) or horizontally (single line, see the 2nd example above)

Well, that’s it. Thanks for reading .

← PreviousNext →