[JavaScript] Controlling Multi-Way Branching with switch Statements and Fall-Through

目次

Overview

When you want to determine if a variable’s value matches a “specific constant” (number or string) and branch your logic in multiple directions, using a switch statement can be more readable than repeating if...else if. This article explains the basic syntax of the switch statement, the essential role of the break statement, and the “fall-through” technique for handling multiple conditions at once.

Specifications (Input/Output)

  • Input: A target string for judgment (e.g., product category, status code).
  • Output: Console output of messages matching the condition.

Basic Usage

You write case value: labels inside a switch (expression) { ... } block. If the result of the expression is strictly equal (===) to a case value, the processes under that label are executed. Use default: for the process when no case matches.

Full Code (HTML / JavaScript)

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>switch Statement Demo</title>
    <script src="switch-demo.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Please check the Console</h1>
        <p>The results of the switch statement branching are output to the log.</p>
    </div>
</body>
</html>

JavaScript (switch-demo.js)

This code includes basic branching and an advanced pattern for grouping multiple values.

/**
 * 1. Basic switch Statement
 * Displays the price based on the type of fruit.
 */
const checkPrice = (fruitName) => {
    console.log(`--- Checking Product: ${fruitName} ---`);

    switch (fruitName) {
        case "apple":
            console.log("Apples are 150 yen.");
            break; // Stop here and exit the block
            
        case "orange":
            console.log("Oranges are 50 yen.");
            break;

        case "grape":
            console.log("Grapes are 400 yen.");
            break;

        default:
            // Process when no case matches
            console.log("That product is not available.");
            break;
    }
};

checkPrice("apple");
checkPrice("watermelon");


/**
 * 2. Grouping Multiple Conditions (Fall-Through)
 * You can create "OR" conditions by writing case labels consecutively.
 */
const checkCategory = (item) => {
    console.log(`--- Determining Category: ${item} ---`);

    switch (item) {
        // If "apple" OR "orange"
        case "apple":
        case "orange":
            console.log("Category: Fruit");
            break;

        // If "carrot", "potato", OR "onion"
        case "carrot":
        case "potato":
        case "onion":
            console.log("Category: Vegetable");
            break;

        default:
            console.log("Category: Others");
            break;
    }
};

checkCategory("orange"); // Category: Fruit
checkCategory("potato"); // Category: Vegetable

Customization Points

  • Comparison is Strict Equality: switch uses === for comparisons. You must be aware of types, as the numerical 10 and the string "10" will lead to different branches.
  • Using with return: When using switch inside a function, you can write return value; instead of break. This returns a value and exits the function immediately, which often makes the code shorter.

Important Points

  • Forgetting break (Unintended Passing): If you forget to write break at the end of a case, the code will continue executing the next case even after a match (this is called “fall-through”). Unless this is intentional, always include a break.
  • Shared Scope: The entire switch block shares a single scope. If you declare let x = 1; in one case, you cannot use the same variable name x in another case. To use variable declarations, wrap the case content in { ... } to create a block scope.

Advanced Usage

Using Expressions for Condition Judgment

By writing switch (true), you can use conditional expressions in each case. However, use this sparingly as if...else if is usually easier to read.

const score = 85;

switch (true) {
    case score >= 90:
        console.log("Grade S");
        break;
    case score >= 70:
        console.log("Grade A"); // This runs
        break;
    default:
        console.log("Grade B");
}

Summary

The switch statement is powerful when a variable’s value needs to branch into fixed options like “A, B, or C.” It makes the structure clearer than a series of if statements. Be careful not to forget break statements. When you want to handle multiple values with the same logic, intentionally omitting break to line up case labels is an effective technique.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次