The switch Statement
A switch compares one value against a list of exact matches, which reads better than a long chain of else ifs.
switch compares with strict equality against each case. Without a break, execution falls through to the next case, which is a bug by default and a useful tool when deliberate.
EXERCISE
1One Value, Many Exact Matches
When a decision is about which single value a variable holds, a switch says that more plainly than a chain of comparisons.
The chain, and the switch that replaces it:
const day = "tue";
// As an if chain:
if (day === "mon") console.log("Start of week");
else if (day === "tue") console.log("Second day");
else if (day === "wed") console.log("Midweek");
else console.log("Some other day");
// As a switch:
switch (day) {
case "mon":
console.log("Start of week");
break;
case "tue":
console.log("Second day"); // this runs
break;
case "wed":
console.log("Midweek");
break;
default:
console.log("Some other day");
}
The parts:
switch (value) { // the value being examined, once
case match: // compared with === against value
// code
break; // stop here, leave the switch
default: // when nothing matched (optional, goes last)
// code
}
Matching is strict, which catches people out:
const code = "1";
switch (code) {
case 1:
console.log("number one"); // does NOT run
break;
case "1":
console.log("string one"); // this runs
break;
}
// switch uses ===, so "1" and 1 are different cases.
Reach for switch when you are asking "which one of these exact values is it?", and stay with if when you are asking anything else. A switch cannot express score >= 90, because it compares for equality only, and forcing ranges into one produces code far worse than the chain it replaced.
EXERCISE
2break, and the Fall-Through Trap
Leaving out a break does not end the case, it carries on into the next one, which is the single most common switch bug.
A case is a label, not a block. Execution jumps to the matching label and then keeps going until it hits a break.
The bug:
const role = "editor";
switch (role) {
case "editor":
console.log("Can edit");
case "viewer":
console.log("Can view");
case "guest":
console.log("Limited access");
}
// Can edit
// Can view
// Limited access
// All three! Nothing stopped it.
With breaks, as intended:
switch (role) {
case "editor":
console.log("Can edit");
break;
case "viewer":
console.log("Can view");
break;
case "guest":
console.log("Limited access");
break;
}
// Can edit
Fall-through on purpose, which is the one good use:
const day = "sat";
switch (day) {
case "sat":
case "sun":
console.log("Weekend");
break;
case "mon":
case "tue":
case "wed":
case "thu":
case "fri":
console.log("Weekday");
break;
}
// Weekend
// Stacked cases with no code between them share one block.
// This is deliberate and readable. Add a comment when you do it
// with code in between, so a reader knows it is not a missing break.
Pro Tip: Write the
breakfirst and the case body second, as a habit. A missing break produces no error and no warning, and the symptom is that several unrelated things happen at once, which sends people looking at the wrong code entirely. Stacked empty cases are the exception, and they are obviously deliberate because there is nothing between them.
EXERCISE
3default, and Returning Instead of Breaking
The default case handles everything you did not list, and inside a function you can skip break entirely by returning.
default catches the unlisted values:
function describe(status) {
switch (status) {
case "active":
return "Running now";
case "paused":
return "Temporarily stopped";
default:
return `Unknown status: ${status}`;
}
}
console.log(describe("active")); // Running now
console.log(describe("deleted")); // Unknown status: deleted
Notice there are no break statements. return leaves the whole function, so it ends the switch as well. This is the shape you will write most often.
default does not have to be last, but it should be:
// Legal, and confusing. Put it at the end.
switch (x) {
default:
console.log("fallback");
break;
case 1:
console.log("one");
}
Declaring a variable inside a case needs braces:
const action = "add";
switch (action) {
case "add": {
const result = 2 + 2; // braces give this its own block
console.log(result);
break;
}
case "subtract": {
const result = 5 - 2; // same name, different block, no clash
console.log(result);
break;
}
}
// Without the braces, both cases share one scope and the
// second const throws: "Identifier 'result' has already been declared".
Pro Tip: Inside a function, prefer
returnoverbreak. It removes every chance of a fall-through bug, it makes each case obviously independent, and it usually means the whole switch is the body of a small, focused function that does one job. That is a good shape to aim for.
