When one value must be compared with several fixed choices, switch is often clearer than a long if-else if chain. JavaScript evaluates the selector once, then jumps to the matching case.
Basic structure
Each case contains a constant followed by a colon. A match runs that branch, break exits the switch, and default handles every unmatched value.
let day = 4;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
case 5:
console.log("Friday");
break;
case 6:
case 7:
console.log("Weekend");
break;
default:
console.log("Invalid day");
}This example covers all seven days. Cases 6 and 7 are adjacent and intentionally share one body because they produce the same result.
break and fall-through
Without break, execution continues into the following case; this is called fall-through. Unless several labels intentionally share one body, end each independent branch with break.
Each case contains an expression. JavaScript compares it with the selector using strict equality (===), so the number 1 and the string "1" do not match. Strings and numbers are both common selector values.
Execution order
- Evaluate the switch selector.
- Find an equal case; use default if none matches.
- Execute statements from the matched position.
- Exit at break or at the end of the switch.
switch Step Debugger
Choose a membership tier. Click the highlighted line or Run current line; exactly one statement executes each time.
KNOWLEDGE QUIZ
Build a membership checkout calculator
Read a membership tier and order subtotal, use switch to select a discount, and calculate the amount due.
- Read an integer tier and a floating-point amount.
- Tier 0 receives no discount; tiers 1, 2, and 3 receive 5%, 10%, and 15% discounts.
- Use switch to assign discount; print an error and stop for an invalid tier.
- Calculate amount * (1 - discount) and print the amount due with two decimal places.