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:
switchuses===for comparisons. You must be aware of types, as the numerical10and the string"10"will lead to different branches. - Using with return: When using
switchinside a function, you can writereturn value;instead ofbreak. 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
breakat the end of acase, the code will continue executing the nextcaseeven after a match (this is called “fall-through”). Unless this is intentional, always include abreak. - Shared Scope: The entire
switchblock shares a single scope. If you declarelet x = 1;in onecase, you cannot use the same variable namexin anothercase. To use variable declarations, wrap thecasecontent 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.
