In the previous tutorial, we have seen if-else statements. In this tutorial, you will learn about the javascript switch statements.

The JavaScript Switch statement

The javascript switch statement is a flow control statement, It is similar to the if-else statement.

Syntax

switch (expression) {
   case condition 1: statement 1;
   break;
   
   case condition 2: statement 2;
   break;
   .
   .
   case condition n: statement n;
   break;
   
   default: default_statement;
}
Flow chart of a switch statement
Switch statement flow chart
As you can see in the above flow chart, If case_1 is true statement_1 will be executed, if it is false jump to case_2 and evaluate it, if it is true statement_2 will be executed. Similarly, it evaluates each case.  
If the expression doesn't match any one of the case values the default statement will be executed.
The break keyword uses the execution to jump/terminate out of the switch statement if the previous case satisfies the expression.

Example 1: Identify whether a number is even or odd using a switch statement.
<html>
    <body>
        <script>
            var n=30;
            var m=30%2;
            switch(m){
                case 0:
                document.write(n+" is even number");
                break;
                default:
                document.write(n+"is odd number");
            }
        </script>
    </body>
</html>
Output 
Example 2: Display a day based on the given day numbers with the Switch statement.
<html>
    <body>
        <script>
          var day="2"
          var name;
            switch(day){
                case '1':
                name="Sunday";
                break;
                case '2':
                name="Monday";
                break;
                case '3':
                name="Tuesday";
                break;
                case '4':
                name="wednesday";
                break;
                case '5':
                name="Thursday";
                break;
                case '6':
                name="Friday";
                break;
                case '7':
                name="Saterday";
                break;
                default:
                    name="Invalid day";
            }
            document.write(name);
        </script>
    </body>
</html>
Output
Monday