QUIZGUM

Coding Class

Quizgum : switch

switch statement

Let's learn about the switch statement.

Like the if statement, the switch statement belongs to one of the conditional statements. Usage is ...

switch (variable){
    case value A :
        Value A when executed statements;
        break;

    case value B :
        Value A when executed statements;
        break;

    case value C :
        Value A when executed statements;
        break;

    case value D :
        Value A when executed statements;
        break;

    case value E :
        Value A when executed statements;
        break;

    default :
        The above values A ~ E both when not execute the statement;
}

The value can be a string or a number. ^^
I'm not sure how to use the above, so let's look at the actual example.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript</title>
<script>
    favorite = "disneyland";
    switch (favorite){
        case "mickey" :
            document.write("I Love mickey");
            break;

        case "disneyland" :
            document.write("I Love disneyland");
            break;

        case "robot" :
            document.write("I Love robot");
            break;

        case "ipad" :
            document.write("I Love ipad");
            break;

        case "apple" :
            document.write("I Love apple");
            break;

        case "macbook" :
            document.write("I Love macbook");
            break;

        default :
            document.write("nothing");
    }
</script>
</head>
<body>
</body>
</html>

break in switch statement; As you can see, break means to exit. In other words, it does not execute subsequent case statements.
Remove the break statement from the source above and test it. What the result is;

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript</title>
<script>
    favorite = "disneyland";
    switch (favorite){
        case "mickey" :
            document.write("I Love mickey");

        case "disneyland" :
            document.write("I Love disneyland");

        case "robot" :
            document.write("I Love robot");

        case "ipad" :
            document.write("I Love ipad");

        case "apple" :
            document.write("I Love apple");

        case "macbook" :
            document.write("I Love macbook");

        default :
            document.write("nothing");
    }
</script>
</head>
<body>
</body>
</html>

If you look at the result, after executing the case statement that meets the condition, the next case statement will be executed all the time because there is no break statement.
Please keep in mind the benefits.
This concludes the switch statement. ^^