Switch Statements in JavaScript
Introduction
A switch statement compares one value against multiple cases and runs the matching branch. It is often cleaner than long else if chains when you compare the same variable against many constants. This chapter covers switch, break, default, and fall-through rules.
Prerequisites
Basic switch Syntax
break stops the switch after a case runs. Without break, execution falls through to the next case.
Strict Comparison (===)
switch uses strict equality (===), not loose ==:
// Number 1 does not match string "1"
const code = 1;
switch (code) {
case 1:
console.log("Numeric one");
break;
case "1":
console.log("String one");
break;
}default Case
Handles values that match no case:
Fall-Through (Intentional)
Sometimes multiple cases share logic:
Warning
Accidental fall-through is a common bug. Add break unless grouping is intentional—and comment why.
switch vs if / else if
Use switch when | Use if when |
|---|---|
| Same variable, many discrete values | Ranges (score > 80) |
| Constants / enums | Complex boolean logic |
| Readable command routing | Few branches (2–3) |
Mini Example: HTTP Status Handler
FAQ
Can switch use ranges like score >= 90?
Not directly—each case is one value. Use if chains or convert to buckets first.
Does switch work on strings?
Yes—very common for commands, roles, and status codes.
What is a switch (true) pattern?
An advanced style for complex conditions—learn if deeply first.
What comes next?
For loops and while loops.