switch Statements in JavaScript and Their Pitfalls
A switch compares with strict equality and falls through to the next case unless you break. See fallthrough, shared scope, switch true and lookup tables.

A switch looks like a tidy way to branch on a value, and it carries three behaviors that an if chain does not: it compares with strict equality, it falls through from one case to the next, and its cases share a single scope. Each is the source of a familiar bug, and each has a use once you know it is there. This post shows the matching rule, the fallthrough that people forget and the grouping that people use deliberately, the scope trap, the switch (true) pattern and the alternatives. Output is from Node.js 24 as an ES module. The scope detail connects to block scope versus function scope, and the equality rule to loose versus strict equality.
Matching uses strict equality
The expression in the parentheses is compared with each case value using ===, and no type conversion happens.
function describe(value) {
switch (value) {
case 1:
return "number one";
case "1":
return "string one";
case NaN:
return "not a number";
case null:
return "null";
case undefined:
return "undefined";
default:
return "no match";
}
}
console.log(describe(1));
console.log(describe("1"));
console.log(describe(NaN));
console.log(describe(null));
console.log(describe(undefined));
console.log(describe(true));
console.log(describe(new Number(1)));number one
string one
no match
null
undefined
no match
no matchThe number and the string version of one matched different cases. case NaN never matched, even for NaN, because strict equality says NaN is not equal to anything, itself included. To branch on NaN, test it before the switch with Number.isNaN(). A wrapper object such as new Number(1) is also a different value from the primitive. A frequent real bug is a numeric id from a form, which is a string, entering a switch written with numeric cases and matching nothing.
Fallthrough
When a case runs and reaches the end without break, return or throw, execution continues into the next case, even if its test would have failed.
function levelNames(level) {
const names = [];
switch (level) {
case 3:
names.push("three");
case 2:
names.push("two");
case 1:
names.push("one");
break;
case 0:
names.push("zero");
default:
names.push("fallback");
}
return names;
}
console.log(levelNames(3));
console.log(levelNames(2));
console.log(levelNames(0));
console.log(levelNames(9));[ 'three', 'two', 'one' ]
[ 'two', 'one' ]
[ 'zero', 'fallback' ]
[ 'fallback' ]Level 3 ran its own case, then the cases for 2 and 1, and stopped at the break. Level 0 fell into default, which is rarely intended. The usual bug is a missing break, where the author wanted one branch and got several. ESLint's no-fallthrough rule reports a case that falls through without a comment, and it accepts a // falls through comment as a signal that it is deliberate.
Grouping cases on purpose
The deliberate use of fallthrough is to share one body between several values. Cases with no statements between them form a group, and no comment is needed.
function category(day) {
switch (day) {
case "sat":
case "sun":
return "weekend";
case "mon":
case "tue":
case "wed":
case "thu":
case "fri":
return "weekday";
default:
return "unknown";
}
}
console.log(["sat", "tue", "xyz"].map(category));
function statusClass(code) {
switch (Math.floor(code / 100)) {
case 2:
return "success";
case 3:
return "redirect";
case 4:
case 5:
return "error";
default:
return "other";
}
}
console.log([200, 301, 404, 503, 102].map(statusClass));[ 'weekend', 'weekday', 'unknown' ]
[ 'success', 'redirect', 'error', 'error', 'other' ]Grouped cases read like a list of alternatives. The second function turns a continuous range into discrete cases by dividing, which is a good use of switch on a computed value. When a function returns from every case, no break is needed, and that is the cleanest form.
One scope for all cases
The body of a switch is a single block, so a let or const declared in one case is visible in the others, and a repeated name is an error.
try {
new Function(`
switch (1) {
case 1:
const label = "one";
break;
case 2:
const label = "two";
break;
}
`);
} catch (error) {
console.log(error.name + ": " + error.message);
}
function render(kind) {
switch (kind) {
case "a": {
const label = "alpha";
return label;
}
case "b": {
const label = "beta";
return label;
}
default:
return "none";
}
}
console.log(render("a"), render("b"), render("z"));
function peek(n) {
switch (n) {
case 1:
let hidden = "set in case 1";
return hidden;
case 2:
try {
return hidden;
} catch (error) {
return error.name;
}
}
}
console.log(peek(1), peek(2));SyntaxError: Identifier 'label' has already been declared
alpha beta none
set in case 1 ReferenceErrorThe duplicate declarations were rejected at parse time. Wrapping each case body in braces gave each its own scope, which is the fix. The last example shows the subtler failure: hidden exists in the whole switch, so case 2 can reach the name, and since its declaration never ran, the read throws from the dead zone, a behavior described in the post on the temporal dead zone. Use braces whenever a case declares anything.
default placement
default can appear anywhere in the list, and the engine tests every case first and falls back to default only if none match. Position matters for fallthrough.
function pick(value) {
const trail = [];
switch (value) {
case "a":
trail.push("a");
break;
default:
trail.push("default");
case "b":
trail.push("b");
break;
}
return trail;
}
console.log(pick("a"));
console.log(pick("b"));
console.log(pick("z"));[ 'a' ]
[ 'b' ]
[ 'default', 'b' ]With an unmatched value, default ran and then fell through into "b", because it lacks a break. A default in the middle is legal and confusing, so keep it last, where fallthrough cannot reach another case.
switch (true)
Putting true in the parentheses lets each case hold a condition, and the first true one wins. It is a readable replacement for a long if and else if chain.
function band(score) {
switch (true) {
case score >= 90:
return "A";
case score >= 75:
return "B";
case score >= 50:
return "C";
default:
return "F";
}
}
console.log([95, 80, 60, 10].map(band));
console.log(band("90"));
console.log(band(NaN));[ 'A', 'B', 'C', 'F' ]
A
FThe two extra calls show what the conditions let through: band("90") returned "A" because the >= operator converts the string to a number, and band(NaN) fell to "F" because every comparison with NaN is false. Each case expression must be exactly true, not merely truthy, because of the strict comparison. A condition that evaluates to a truthy non-boolean, such as score && score > 5 with score zero, produces 0 or a number rather than true, and never matches. The pattern is fine for ranges. We would write an if chain in the same situation without strong feelings, and a lookup table of thresholds if the list grows.
Testing a switch
A switch is easy to test because the input space is small, and a table of expected results covers every branch, including the ones people forget: the default, the boundary between two ranges and a value of the wrong type.
import { test } from "node:test";
import assert from "node:assert/strict";
function statusClass(code) {
switch (Math.floor(code / 100)) {
case 2:
return "success";
case 3:
return "redirect";
case 4:
case 5:
return "error";
default:
return "other";
}
}
const table = [
[200, "success"],
[299, "success"],
[300, "redirect"],
[404, "error"],
[500, "error"],
[199, "other"],
[600, "other"],
];
for (const [code, expected] of table) {
test(`status ${code} is ${expected}`, () => {
assert.equal(statusClass(code), expected);
});
}Run it with node --test on Node.js 24. The boundary rows, 199 and 299, are the ones a hand-written range check tends to get wrong, and the table makes them visible. When a new status class is added to the function, a new row costs one line.
An object or Map instead
When a switch only maps one value to another, a plain object or a Map is shorter, declarative and easy to extend.
const handlers = {
create: (name) => `created ${name}`,
delete: (name) => `deleted ${name}`,
};
function run(action, name) {
const handler = Object.hasOwn(handlers, action) ? handlers[action] : () => `unknown action ${action}`;
return handler(name);
}
console.log(run("create", "a"), run("delete", "b"), run("rename", "c"));
console.log(run("toString", "d"));
const labels = new Map([
[200, "ok"],
[404, "not found"],
]);
console.log(labels.get(404), labels.get(500) ?? "other");created a deleted b unknown action rename
unknown action toString
not found otherThe table maps each action to a function, and a new action is one new entry. The Object.hasOwn guard prevents an inherited name such as toString from being treated as an action, and without it, run("toString") would call the inherited method. A Map avoids that problem entirely and allows non-string keys, such as the numeric status codes above.
TypeScript and exhaustive checks
In TypeScript, a switch on a union of literals can be checked for completeness. Assigning the value to never in default makes the compiler complain if a case is missing.
type Shape = { kind: "circle"; radius: number } | { kind: "square"; side: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.side ** 2;
default: {
const unreachable: never = shape;
throw new Error("unhandled shape: " + JSON.stringify(unreachable));
}
}
}Adding a third shape to the union makes the assignment to never a compile error until the new case is written. That check is the strongest reason to keep a switch over a discriminated union and not replace it with a lookup table.
Reading a switch quickly
Three scans find most problems in a switch you did not write. Look at the end of each case for a break, return or throw, and mark the ones that lack it. Look for declarations inside cases without braces. And look at what the discriminant can be at runtime, since a value that arrives as a string from a URL or a form will never match a numeric case. Doing the three scans takes under a minute and catches the bugs that survive unit tests written with the type the author had in mind.
When to use something else
Prefer an object or Map for pure mappings, an if chain for two or three conditions and polymorphism, with a method on each class, when the branches are behavior that grows with the types. A switch earns its place for a small, closed set of values with different statements, especially with exhaustive checking.
The statement is defined in the specification under the switch statement, and MDN's page on switch covers the fallthrough and scoping rules.


