Sub topic 6
Branching on One Value with switch
A switch statement compares one value against a list of candidates and runs the code for the first one that matches. It does the same job as an if/else if chain whose every condition is x === something, but it puts the shared value in one place. This chapter covers how switch matches, how fall-through works and when it hurts you, how scoping behaves inside cases, and when to pick another construct.
This chapter assumes you know how if/else if/else chains work and how strict equality (===) differs from loose equality (==), both covered in earlier chapters. You should also be comfortable writing functions.
The Shape of a switch
function httpStatusText(code) {
switch (code) {
case 200:
return "OK";
case 404:
return "Not Found";
case 500:
return "Internal Server Error";
default:
return "Unknown";
}
}
console.log(httpStatusText(404)); // "Not Found"
console.log(httpStatusText(418)); // "Unknown"The parts are:
- The discriminant is the expression in parentheses after
switch. It is evaluated once. - Each case clause is
case expression:followed by zero or more statements. - The optional default clause runs when no case matches.
Here each case ends with return, which leaves the function and therefore the switch too. Outside a function, or when you want to keep going after the switch, you end cases with break instead.
How Matching Works
JavaScript evaluates the discriminant, then checks the case expressions from top to bottom using strict equality (===). When one matches, execution jumps to that clause and continues from there. If none matches, execution jumps to default if it exists. Otherwise the whole switch is skipped.
Strict equality means no type conversion happens. This is a common source of "my case never runs" bugs, especially with values read from forms, URLs, or localStorage, which are always strings.
function pageName(page) {
switch (page) {
case 1:
return "Home";
case 2:
return "About";
default:
return "Not found";
}
}
console.log(pageName(1)); // "Home"
console.log(pageName("1")); // "Not found" because "1" !== 1
const fromUrl = "2";
console.log(pageName(Number(fromUrl))); // "About"Convert the discriminant to the right type once, before the switch, rather than duplicating cases for both 1 and "1".
Strict equality has two more edge cases that carry over to switch:
NaNnever matches anything, not evencase NaN:, becauseNaN === NaNisfalse. Test for it withNumber.isNaNbefore theswitch.- Objects and arrays match only if they are the same reference.
case [1, 2]:creates a new array and will never match a discriminant array.
Case expressions do not have to be literals. They can be any expression, such as a constant or a function call. They are evaluated in order, one at a time, and only until a match is found, so the expressions in later cases may never run.
Fall-Through
Once a case matches, JavaScript does not stop at the next case label. It keeps executing statements downward, through later case labels, until it reaches break, return, throw, or the end of the switch. This is called fall-through.
Here is what happens when you forget break:
function permissions(level) {
const granted = [];
switch (level) {
case 3:
granted.push("delete");
case 2:
granted.push("edit");
case 1:
granted.push("view");
break;
default:
granted.push("none");
}
return granted;
}
console.log(permissions(3)); // ["delete", "edit", "view"]
console.log(permissions(2)); // ["edit", "view"]
console.log(permissions(1)); // ["view"]
console.log(permissions(0)); // ["none"]This example falls through on purpose, because each level includes the permissions of the levels below it. More often, a missing break is a bug: two branches run when you meant one, and nothing raises an error.
Grouping Cases
The most common deliberate use of fall-through is stacking empty case labels so several values share one body:
function dayType(day) {
switch (day) {
case "Sat":
case "Sun":
return "weekend";
default:
return "weekday";
}
}
console.log(dayType("Sun")); // "weekend"
console.log(dayType("Mon")); // "weekday"An empty case has no statements, so falling from "Sat" into "Sun" is harmless and easy to read. Linters do not flag this pattern.
Where default Goes
default is usually last, but it can appear anywhere. Its position does not change when it is chosen: it runs only after every case has failed to match. Its position does change what it falls through into.
function trace(x) {
const out = [];
switch (x) {
case 1:
out.push("one");
break;
default:
out.push("default");
case 2:
out.push("two");
}
return out;
}
console.log(trace(1)); // ["one"]
console.log(trace(2)); // ["two"]
console.log(trace(5)); // ["default", "two"]For 5, no case matches, so execution starts at default, and because there is no break, it falls into case 2. Code like this is legal but confusing. Keep default last and end it with break (or return) even though it is not strictly needed. That way, adding a case after it later cannot introduce accidental fall-through.
Scoping Inside a switch
The whole body of a switch is a single block. Case labels do not create their own scopes. So declaring the same let or const name in two cases is a SyntaxError:
// SyntaxError: Identifier 'message' has already been declared
// switch (action) {
// case "save":
// const message = "Saved";
// break;
// case "delete":
// const message = "Deleted";
// break;
// }There is a subtler problem too. A let declared in one case is visible in later cases, but it is uninitialized there unless its own case ran. Using it throws a ReferenceError because of the temporal dead zone.
The fix is to wrap each case body in braces, which gives each one its own block:
function notify(action) {
switch (action) {
case "save": {
const message = "Saved";
return message.toUpperCase();
}
case "delete": {
const message = "Deleted";
return message.toUpperCase();
}
default:
return "UNKNOWN";
}
}
console.log(notify("save")); // "SAVED"
console.log(notify("delete")); // "DELETED"The braces do not affect fall-through or break. They only limit the scope of declarations.
The switch (true) Pattern
You will sometimes see switch (true) used to test ranges:
function grade(score) {
switch (true) {
case score >= 90:
return "A";
case score >= 80:
return "B";
default:
return "C or below";
}
}
console.log(grade(85)); // "B"This works because each case expression evaluates to a boolean, and the first one that is === true wins. It has a trap: the case must produce exactly true, not merely a truthy value. case user && user.name: evaluates to a string such as "Ada", and "Ada" === true is false, so the case silently never matches. An if/else if chain says the same thing more directly and treats truthy values as you would expect, so most style guides prefer it for ranges.
Choosing switch or Something Else
| Situation | Good fit | Why |
|---|---|---|
| One value compared against several fixed constants, each with different statements | `switch` | The discriminant appears once and cases line up visually |
| Several values share a body | `switch` with stacked cases | Grouping reads clearly |
| Range checks or conditions on different variables | `if`/`else if` | `switch` only tests `===`; `switch (true)` hides intent |
| Each value maps to a plain result, with no extra logic | Lookup object or `Map` | Data, not code; covered in the final chapter |
| Exactly two outcomes producing a value | Conditional operator | Shorter and an expression |
Inside a function, ending cases with return avoids both break clutter and accidental fall-through. When the switch must assign a variable instead, every non-empty case needs a break.
Exercise
What does classify("0") return, and why? function classify(v) { switch (v) { case 0: return "zero"; case false: return "false"; default: return "other"; } }
Show answer
It returns "other". switch uses strict equality, so the string "0" is not equal to the number 0 or to false. No type conversion happens, so execution goes to default.
Exercise
What does this code log? let log = []; switch (2) { case 1: log.push("a"); case 2: log.push("b"); case 3: log.push("c"); break; case 4: log.push("d"); } console.log(log);
Show answer
It logs ["b", "c"]. Execution starts at case 2, pushes "b", falls through into case 3 because there is no break, pushes "c", and then stops at the break. Case 1 and case 4 never run.
Exercise
A teammate writes switch (true) { case input && input.trim(): process(input); break; default: showError(); } and reports that showError always runs, even for non-empty input. Explain the bug and give a fix.
Show answer
The case expression evaluates to a string (the trimmed input) or to a falsy value, never to exactly true, and switch compares with ===, so the case never matches. Fix it by using an if statement, if (input && input.trim()) { process(input); } else { showError(); }, or by forcing a boolean with case Boolean(input && input.trim()):.