Sub topic 6
Branching on One Value with switch
This chapter assumes you can write if/else if chains and know how strict equality (===) differs from loose equality (==). A switch statement takes one value and compares it against a list of case values. It is often easier to read than a long if chain that tests the same variable over and over.
How switch Matches
JavaScript evaluates the expression in switch (...) once. It then checks each case from top to bottom using strict equality. At the first match, execution starts at that case and keeps going until it reaches a break, a return, or the end of the switch. If nothing matches, the default clause runs, if there is one.
function dayType(day) {
switch (day) {
case "Sat":
case "Sun":
return "weekend";
default:
return "weekday";
}
}
console.log(dayType("Sun")); // "weekend"
console.log(dayType("Mon")); // "weekday"The "Sat" case has no body, so it falls through to the code under "Sun". Stacking empty case labels like this is the normal way to send several values to the same code.
Common Errors
Forgetting break
Outside a function that uses return, each case needs a break. If you leave it out, execution falls into the next case's body as well. This is easy to miss.
function describe(level) {
const messages = [];
switch (level) {
case 1:
messages.push("low");
case 2:
messages.push("medium");
break;
case 3:
messages.push("high");
break;
}
return messages;
}
console.log(describe(1)); // ["low", "medium"] (fell through)
console.log(describe(2)); // ["medium"]Type mismatches
switch uses ===, so "1" does not match case 1. Values from form fields and URLs arrive as strings. Convert them first:
const input = "2";
switch (Number(input)) {
case 2:
console.log("matched two");
break;
default:
console.log("no match");
}
// "matched two"Declarations colliding across cases
The whole switch body is a single block. If two cases each declare const msg, you get a SyntaxError. Wrap each case body in braces so it gets its own scope:
function format(kind) {
switch (kind) {
case "error": {
const msg = "Something failed";
return msg.toUpperCase();
}
case "info": {
const msg = "All good";
return msg;
}
default:
return "";
}
}
console.log(format("error")); // "SOMETHING FAILED"Where default Goes
default can appear anywhere in the list, but it only runs when no case matches. Put it last. That keeps the order clear and means a missing break after it cannot cause a surprise.
When to Use switch
| Situation | Better choice |
|---|---|
| One value compared to several fixed constants | `switch` |
| Ranges such as `score >= 90` | `if`/`else if` |
| Mapping a key directly to a value | Object lookup (covered in a later chapter) |
| Choosing between two values | Conditional operator |
You may see switch (true) with conditions as the cases. It works, but an if chain is usually clearer for ranges.
Exercise
What does this log, and why? const x = "0"; switch (x) { case 0: console.log("zero"); break; case "0": console.log("string zero"); default: console.log("other"); }
Show answer
It logs "string zero" and then "other". The case 0 does not match because switch uses strict equality and "0" is a string. The case "0" matches, and since it has no break, execution falls through into default.
Exercise
Rewrite a switch on fruit so that "apple" and "pear" both return "pome", "cherry" returns "drupe", and anything else returns "unknown".
Show answer
function kind(fruit) { switch (fruit) { case "apple": case "pear": return "pome"; case "cherry": return "drupe"; default: return "unknown"; } }