JavaScript Switch

JavaScript Switch statement is used to execute different set of statements based on different conditions. It is similar to If-Else statement, but excels in code simplicity and works greatly with numbers, characters and Strings.

Syntax

switch(expression){
    case value_1 : 
        // set of statements
        break;
    case value_2 : 
        // set of statements
        break;
    default : 
        // set of statements
}

Explanation: The switch expression is evaluated and each case value is matched against it. When there is a match for a case value, the corresponding set of statements are executed.

  • break statement is must, for each case block, for desired conditional execution.
  • default block is executed when no case value is matched.

Examples

The following example demonstrates the usage of switch statement.

index.html

<!doctype html>
<html>
<body>
    <h1>JavaScript Switch Statement Example</h1>
    <p id="message"></p>
    <script>
        <!-- your JavaScript goes here -->
        <!-- try changing the data in "value" and run -->
        var value=2;
        var message='';
        switch(value){
            case 1:
                message += "Value is 1.";
                break;
            case 2:
                message += "Value is 2.";
                message += " This is second statement.";
                break;
            case 3:
                message += "Value is 3.";
                break;
            default :
                message += "Value is default."
        }
        document.getElementById("message").innerHTML = message;
    </script>
</body>
</html>

Note: Please note that there is break statement at the end of every case block. Failing to provide a break statement results in not breaking of switch statement. This makes the subsequent case blocks executed.

Following is an example demonstrating such scenario, where break is not used for case blocks in switch statement.

index.html

<!doctype html>
<html>
<body>
    <h1>JavaScript Switch Statement Example</h1>
    <p id="message"></p>
    <script>
        <!-- your JavaScript goes here -->
        <!-- try changing the data in "value" and run -->
        var value=2;
        var message='';
        switch(value){
            case 1:
                message += "Value is 1.";
            case 2:
                message += "Value is 2.";
                message += " This is second statement.";
            case 3:
                message += "Value is 3.";
            default :
                message += "Value is default."
        }
        document.getElementById("message").innerHTML = message;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we have learnt the syntax and working of JavaScript Switch statement with examples.