switch: Multi-Way Branching Without RepetitionThe 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.
break KeywordEvery 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":.
switch and Object Lookup AlternativeWhen 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");
break after non-returning cases: Always end each non-empty case with break or return so the next branch does not run accidentally.const or let with the same name in two cases: A switch shares one block scope across all cases, causing a SyntaxError. Wrap a case body in { ... } braces when declaring local variables.case score > 80:: Unless you intentionally write switch (true), standard switch tests exact equality only; use if...else if for ranges.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.
switch use == or ===?JavaScript switch always uses strict === comparison, so no automatic string-to-number conversion occurs.
switch?Use an object or Map when mapping keys directly to values or handler functions without complex multi-step control flow.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.