JavaScript Switch Statement

switch statement is a control-flow statement that tests the value of an expression against multiple cases.

In this tutorial, you will learn about the JavaScript switch statement with the help of examples.

switch statement can replace multiple if checks.

The switch has one or more case blocks and an optional default.

The JavaScript switch statement is used in decision making.

Syntax

switch (expression) {
   case value 1: statement(s)
   break;
   
   case value 2: statement(s)
   break;
   ...
   
   case value n: statement(s)
   break;
   
   default: statement(s)
}

The switch statement uses the strict comparison (===)(the values must be equal in type as well).

The value of expression is checked for a strict equality to the value from the first case then to the second and so on.

If one of the cases matches the expression, then the code inside that case clause will execute.

If multiples cases match the switch statement, then the first case that matches the expression will be used.

The break statements indicate the end of a particular case.

If you omit break statement, the interpreter would continue executing each statement in each of the following cases.

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

If none of the cases match the expression, then the default clause will be executed.

In practice, you often use a switch statement to replace a complicated  if else statements to make the code more readable.

Flowchart

JavaScript Switch Statement Flowchart

Example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Switch Statement Example</title>
</head>

<body>
    <script>
        var grade = 'A';
        document.write("Entering switch block<br />");
        switch (grade) {
            case 'A': document.write("Good job<br />");
                break;

            case 'B': document.write("Pretty good<br />");
                break;

            case 'C': document.write("Passed<br />");
                break;

            case 'D': document.write("Not so good<br />");
                break;

            case 'F': document.write("Failed<br />");
                break;

            default: document.write("Unknown grade<br />")
        }
        document.write("Exiting switch block");
    </script>
    <p>Set the variable to different value and then try...</p>
</body>

</html>