JavaScript Switch Statement

The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if statement that we have learned in previous page. But it is convenient than if..else..if because it can be used with numbers, characters etc.

The signature of JavaScript switch statement is given below.

switch(expression) 
{
    case x:
    // code block
    break;
    case y:
    // code block
    break;
    default:
    // code block
}

This is how it works:

  1. This is how it works:
  2. The value of the expression is compared with the values of each case.
  3. If there is a match, the associated block of code is executed.
  4. If there is no match, the default code block is executed.

The break Keyword

When JavaScript reaches a break keyword, it breaks out of the switch block.

This will stop the execution inside the switch block.

It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.

Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.


The default Keyword

The default keyword specifies the code to run if there is no case match:

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript</title>
    <script>
        var day = 1;

        switch (day) {
            case 0:
                document.write("Today is Monday");
            break;
            case 1:
                document.write("Today is Tuesday");
            break;
            case 2:
                document.write("Today is Wednesday");
            break;
            case 3:
                document.write("Today is Thursday");
            break;
            case 4:
                document.write("Today is Friday");
            break;
            case 5:
                document.write("Today is Saturday");
            break;
            case 6:
                document.write("Today is Sunday");
            break;
            default:
                document.write("Enter the valid Week Day");
        }
    </script>
</head>
<body>
</body>
</html>