JavaScript Switch Statement
The `switch` statement compares a value against multiple possible cases, offering a cleaner alternative to long if/else-if chains when checking one variable against many exact values.
Each `case` uses strict comparison (`===`), and you should include `break` after each case to prevent 'fall-through' into the next case.
Structure
`switch(value) { case a: ...; break; case b: ...; break; default: ...; }` runs the matching case block, or default if none match.
Fall-through
Omitting `break` causes execution to continue into the next case โ sometimes intentional, but usually a bug.
let day = "Mon";
switch (day) {
case "Mon":
console.log("Start of week");
break;
case "Fri":
console.log("Almost weekend");
break;
default:
console.log("Midweek");
}Start of weekThe case matching 'Mon' runs, then break exits the switch.
let x = 2;
switch (x) {
case 1:
case 2:
console.log("One or two");
break;
default:
console.log("Other");
}One or twoGrouped cases (no break between 1 and 2) share the same block.
Key points
- switch compares one value against multiple cases using ===.
- `break` prevents fall-through to the next case.
- `default` runs when no case matches.
- Grouped cases without break can share the same logic block.
