JS Switch
JavaScript switch: Multi-Way Branching Without Repetition
The JavaScript switch statement matches one expression against multiple case clauses using strict equality (===). It replaces long if...else if chains when you test the same variable against fixed values.
Strict Matching and the break Keyword
Every case compares its value to the switch expression using ===, meaning "2" will not match case 2:. Once a case matches, JavaScript runs code from that line downward until it hits a break, a return, or the end of the switch block.
Forgetting break causes fallthrough, where execution spills into the next case even if that case did not match. Intentional fallthrough is useful only when grouping two empty cases together, like case "sat": case "sun":.
Practical switch and Object Lookup Alternative
When each case simply returns a fixed value or label, a plain object or Map is often shorter and cleaner than a switch.
function getRolePermissions(role) {
switch (role) {
case "admin":
return ["read", "write", "delete"];
case "editor":
return ["read", "write"];
case "viewer":
case "guest":
return ["read"];
default:
return [];
}
}
// Alternative lookup map for simple value mapping
const httpStatusText = {
200: "OK",
404: "Not Found",
500: "Server Error",
};
console.log("Viewer perms:", getRolePermissions("viewer"));
console.log("Status 404:", httpStatusText[404] ?? "Unknown");
Common Mistakes to Avoid
- Forgetting
breakafter non-returning cases: Always end each non-emptycasewithbreakorreturnso the next branch does not run accidentally. - Declaring
constorletwith the same name in two cases: Aswitchshares one block scope across all cases, causing aSyntaxError. Wrap a case body in{ ... }braces when declaring local variables. - Trying range checks like
case score > 80:: Unless you intentionally writeswitch (true), standardswitchtests exact equality only; useif...else iffor ranges.
Frequently Asked Questions
Does the default case have to go at the bottom?
JavaScript lets you put default anywhere inside switch, though placing it last is the clearest convention. Add break if you ever place default before another case.
Does switch use == or ===?
JavaScript switch always uses strict === comparison, so no automatic string-to-number conversion occurs.
When is an object lookup better than switch?
Use an object or Map when mapping keys directly to values or handler functions without complex multi-step control flow.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.