When should you use switch?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
switch compares one value against several cases and runs the matching branch. It reads better than a long if...else if chain when you are testing the same expression each time.
switch (status) {
case "pending":
showSpinner();
break;
case "error":
case "timeout": // shared branch
showError();
break;
default:
showResult();
}
Two things to know
Comparison uses strict equality, so case "1" will not match the number 1.
And cases fall through without break. That is deliberate — it is how the shared error/timeout branch above works — but forgetting a break is the classic bug, and the reason linters flag it.
A return inside a function body makes break unnecessary:
function label(status) {
switch (status) {
case "pending": return "Loading";
case "error": return "Failed";
default: return "Done";
}
}
Scope gotcha
The whole switch shares one block scope, so let in one case collides with another. Wrap a case in braces when it declares variables:
case "a": { const x = 1; break; }
case "b": { const x = 2; break; } // fine — separate blocks
The alternative worth considering
For simple value-to-value mapping, an object lookup is shorter and extends without editing logic:
const labels = { pending: "Loading", error: "Failed" };
const text = labels[status] ?? "Done";
Use switch when branches contain real logic, when you want fall-through, or when ranges are involved (switch (true) with conditions in each case). Use a lookup table when you are only mapping keys to values — a two-entry switch is usually worse than the if it replaced.
