JavaScript switch Statement: case Matching, Fall-Through, default and Alternatives
How switch picks a case with strict equality, why missing breaks fall through and when that's useful, grouping cases, default in any position, the let/const scoping trap between cases, switch (true), and when an object or Map lookup is a better choice than a switch.
kvi5hnuCode Sprout team member7 min readOn this page
When one value decides between several fixed options, such as an order status, a command name or an HTTP method, a chain of else if comparisons repeats the same variable over and over. The switch statement expresses that shape directly: evaluate one expression, then jump to the matching case.
function statusMessage(status) {
switch (status) {
case "pending":
return "We've received your order.";
case "shipped":
return "Your order is on its way.";
case "delivered":
return "Your order has arrived.";
default:
return "Unknown status.";
}
}
console.log(statusMessage("shipped"));
console.log(statusMessage("lost"));
Your order is on its way.
Unknown status.
How switch chooses a case
- The expression in
switch (...)is evaluated once. - The
caseexpressions are evaluated in order, from top to bottom, and each is compared with strict equality (===). Evaluation stops at the first match. - Execution jumps to the matching
caselabel and runs from there. - If nothing matches, it jumps to
default:. If there's nodefault, the whole body is skipped.
Strict equality means no type conversion:
function kind(value) {
switch (value) {
case 1: return "number one";
case "1": return "string one";
default: return "something else";
}
}
console.log(kind(1), "|", kind("1"), "|", kind(true));
number one | string one | something else
This is a common surprise when the value comes from a form field, a URL or localStorage, all of which give strings: switch (input.value) never matches case 1:. Convert first, or write the cases as strings.
The === rule also means case NaN: never matches (NaN isn't equal to itself), and an object only matches the same object, never a different object with the same contents.
Case expressions don't have to be constants: case MAX_RETRIES: or case limits.high: are fine. But they're only evaluated until a match is found, so a case with side effects may or may not run. Keep cases to simple values.
break and fall-through
A case label marks where execution starts; it doesn't mark where it ends. Without a break, execution continues straight into the next case's code, and the next, until it reaches a break, a return, or the end of the switch. That's called fall-through:

function notify(level) {
const actions = [];
switch (level) {
case "high":
actions.push("page on-call");
case "medium":
actions.push("send email");
case "low":
actions.push("write log");
}
return actions.join(", ");
}
console.log(notify("high"));
console.log(notify("medium"));
console.log(notify("low"));
page on-call, send email, write log
send email, write log
write log
Here the fall-through is deliberate: a more severe level does everything a lower one does. But far more often, a missing break is a bug: the code for one case accidentally runs the next case too. In a function, return ends the switch just as well as break, which is why return-per-case switches (like the first example) are popular.
When you mean to fall through, say so with a comment. ESLint's no-fallthrough rule (in the recommended set) reports fall-through unless a comment like // falls through marks it as intended.
Grouping cases
The one fall-through everyone uses on purpose: several labels with no code between them share one body:
function dayType(day) {
switch (day) {
case "Sat":
case "Sun":
return "weekend";
default:
return "weekday";
}
}
console.log(dayType("Sun"), dayType("Tue"));
weekend weekday
ESLint doesn't complain about empty cases like these.
default can go anywhere
default is usually last, but it can appear anywhere. It's still only used when no case matches, and fall-through still applies from wherever execution enters:
function trace(x) {
const out = [];
switch (x) {
case 1:
out.push("one");
break;
default:
out.push("default"); // no break: falls into case 2
case 2:
out.push("two");
break;
}
return out.join(",");
}
console.log(trace(1), "|", trace(2), "|", trace(9));
one | two | default,two
Keep default last unless you have a strong reason; readers expect it there (ESLint's default-case-last).
Declaring variables inside cases
The whole body of a switch is one block, so let and const declared in one case belong to the entire switch. Two cases can't declare the same name, and a variable declared in one case is in its temporal dead zone (article 27) when another case tries to use it:
try {
new Function(`switch (x) { case 1: let msg = "a"; break; case 2: let msg = "b"; break; }`);
} catch (err) {
console.log("duplicate declaration:", err.name);
}
function tdz(x) {
switch (x) {
case 1:
let label = "one";
return label;
case 2:
return label; // label exists here, but was never initialized
}
}
try {
tdz(2);
} catch (err) {
console.log("using another case's variable:", err.name);
}
duplicate declaration: SyntaxError
using another case's variable: ReferenceError
The fix is to give each case its own block with braces:
function describe(shape) {
switch (shape.kind) {
case "circle": {
const area = Math.PI * shape.r ** 2;
return `circle, area ${area.toFixed(1)}`;
}
case "square": {
const area = shape.side ** 2; // same name, separate block: fine
return `square, area ${area}`;
}
default:
return "unknown shape";
}
}
console.log(describe({ kind: "circle", r: 1 }), "|", describe({ kind: "square", side: 3 }));
circle, area 3.1 | square, area 9
ESLint's no-case-declarations rule (in the recommended set) flags unbraced declarations in cases.
switch (true) for ranges
switch compares values with ===, so it can't express "between 80 and 89" directly. A known trick is switch (true): each case expression is a condition, and the first one that evaluates to true matches:
function grade(score) {
switch (true) {
case score >= 90: return "A";
case score >= 80: return "B";
case score >= 70: return "C";
default: return "F";
}
}
console.log(grade(95), grade(85), grade(72), grade(10));
A B C F
It works, and some teams like it. Others find it a confusing use of switch, since an if/else if chain says the same thing more directly (article 39). Note that the conditions must evaluate to exactly true: a truthy value like "yes" doesn't match.
Alternatives: lookup objects and Maps
Many switches only map a value to another value or to a function. An object lookup does that in a line, and it can be built, extended or loaded at run time:
const ICONS = { success: "✓", warning: "!", error: "✗" };
const iconFor = (type) => (Object.hasOwn(ICONS, type) ? ICONS[type] : "?");
console.log(iconFor("warning"), iconFor("info"), iconFor("toString"));
const operations = {
add: (a, b) => a + b,
multiply: (a, b) => a * b,
};
const calculate = (op, a, b) => operations[op]?.(a, b) ?? "unsupported";
console.log(calculate("add", 2, 3), calculate("divide", 6, 3));
! ? ?
5 unsupported
Note the Object.hasOwn check: a plain object inherits properties such as toString from Object.prototype, so ICONS["toString"] would return a function instead of falling back. Object.hasOwn, an object created with Object.create(null), or a Map avoids that trap. A Map also allows non-string keys.
Choose switch when each case runs several statements or when fall-through expresses real shared behavior. Choose a lookup when you're mapping keys to values or handlers. Choose if/else if for ranges and unrelated conditions.
Common questions
Is switch faster than if/else?
Sometimes engines can optimize a switch over many integer or string constants into a jump table, but the difference rarely matters. Pick the one that reads better. Unlike C and Java, JavaScript case labels can be any expression evaluated at run time, so this optimization isn't guaranteed.
Do I need a break after the last case or after default?
Not for correctness: there's nothing left to fall into. Many style guides add one anyway, so that a case added later below it doesn't accidentally receive fall-through.
Can I use switch on strings? On objects?
Strings, yes; they're compared with ===, so case and spelling must match exactly. Objects compare by identity, so a case only matches the very same object reference. To switch on an object's kind, switch on a property such as shape.kind.
What happens if two cases have the same value?
Only the first one can ever match; the second is dead code. ESLint's no-duplicate-case (in the recommended set) reports it.
Summary
switch (expr)evaluatesexpronce and jumps to the firstcasewhose value is===to it, or todefault.- Case labels are entry points: without
break(orreturn), execution falls through into the following cases. - Group cases by stacking labels; mark intentional fall-through with a comment.
- The switch body is one scope: wrap each case in braces when it declares
let,constorclass. switch (true)handles ranges, thoughif/else ifis often clearer.- For value-to-value or value-to-function mappings, an object (with
Object.hasOwn) or aMapis usually simpler.
Practice Questions
What does this log?
switch (2) {
case 1: console.log("a");
case 2: console.log("b");
case 3: console.log("c");
break;
case 4: console.log("d");
}
Answer
b and then c. Execution enters at case 2, falls through into case 3, and stops at its break.
A switch on this value has case 1: and case 2: but always runs default. Why?
new URLSearchParams(location.search).get("page")
Answer
get returns a string (or null), and "1" === 1 is false. Use case "1": and case "2":, or convert first with Number(...).
Rewrite as a lookup object: a switch that returns 0.2 for "standard", 0.1 for "reduced" and 0 for "zero", and throws for anything else.
Answer
const RATES = { standard: 0.2, reduced: 0.1, zero: 0 };
function rate(kind) {
if (!Object.hasOwn(RATES, kind)) throw new Error("unknown rate");
return RATES[kind];
}
Note that a shortcut like RATES[kind] || error would be wrong here: RATES.zero is 0, which || treats as missing.
Why does adding const total = ... to two different cases of the same switch fail, and what's the fix?
Answer
All cases share the switch body's single block, so the second const total is a duplicate declaration: a SyntaxError. Wrap each case's statements in their own { } block.
Previous: JavaScript if, else and else if: Conditionals, Braces, Guard Clauses and Common Mistakes
Next: JavaScript Loops: while, do/while and the Classic for Loop

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.