The switch statement provides an elegant multi-way branching mechanism in JavaScript. It evaluates an expression once, matches the result against multiple case clauses, and executes the statements associated with the first matching case.
Crucially, JavaScript switch cases perform strict equality checks (===). Type coercion never occurs:
const userRole = "editor";
switch (userRole) {
case "admin":
console.log("Full Access: Create, Read, Update, Delete");
break; // Exits switch block immediately
case "editor":
console.log("Editorial Access: Create, Read, Update");
break;
case "viewer":
console.log("Read-only Access");
break;
default:
console.log("Access Denied: Unrecognized User Role");
break;
}
While omitting break accidentally is a bug, deliberately omitting break allows grouping multiple cases that share identical logic:
const dayOfWeek = "Saturday";
switch (dayOfWeek) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("Standard Working Day (9 AM - 6 PM)");
break;
case "Saturday":
case "Sunday":
console.log("Weekend! Campus Closed.");
break;
default:
console.log("Invalid Day Name");
}
Exam Question: "Compare switch-case and if-else-if ladder on performance and readability."
| Criteria | Switch Case | If-Else-If Ladder |
|---|---|---|
| Evaluation Type | Evaluates single expression once against discrete constants. | Evaluates arbitrary complex boolean conditions sequentially. |
| Equality Check | Strict equality (===) only. |
Any operator (>, <, &&, ||, ===). |
| Engine Optimization | V8 can compile large switches into jump tables (O(1) dispatch). | Evaluated linearly O(N) from top to bottom. |
How do you repeat an operation when the exact number of iterations is unknown in advance? Proceed to: JavaScript While Loop: Entry-Controlled Loops →
Accelerate your JavaScript mastery by studying these tightly connected core tutorials:
Comparing switch with if-else performance.
Terminating switch cases and loops.
Strict comparison in case evaluations.