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.


switch (expression) {
   case value 1: statement(s)
   case value 2: statement(s)
   case value n: statement(s)
   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.


JavaScript Switch Statement Flowchart


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

    <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>

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

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

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

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

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

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