switch: Multi-Way Branching & FallthroughThe switch statement evaluates an expression against multiple matching case clauses, executing statements associated with the first matching case. Comparisons are evaluated strictly using ===.
flowchart TD
Expr["Evaluate switch(expression)"] --> Case1{"=== Case 1?"}
Case1 -- "Yes" --> Exec1["Execute Case 1 Code"] --> Break1{"break statement?"}
Break1 -- "Yes" --> Exit["Exit Switch Block"]
Break1 -- "No (Fallthrough)" --> Exec2["Execute Case 2 Code"]
Case1 -- "No" --> Case2{"=== Case 2?"}
Case2 -- "Yes" --> Exec2
Case2 -- "No" --> Default["Execute default clause"] --> Exit
| Feature | Behavior | Gotcha / Best Practice |
|---|---|---|
| Matching Equality | Uses strict equality (===). |
Types must match ("1" will NOT match case 1). |
break Statement |
Terminates switch execution. | Omitting break causes unintentional fallthrough. |
default Clause |
Fallback if no case matches. | Place at end of switch block as catch-all. |
| Block Scoping | Shared across switch by default. | Wrap case statements in { ... } to scope variables locally. |
// Demonstrating switch statement, fallthrough grouping, and scoped cases
function getHTTPStatusDescription(statusCode) {
let description = "";
switch (statusCode) {
case 200:
case 201:
// Multi-case fallthrough grouping
description = "Success / Resource Created";
break;
case 400: {
// Scoped block to isolate local variables
const detail = "Bad Request Payload";
description = `Client Error: ${detail}`;
break;
}
case 404:
description = "Resource Not Found";
break;
case 500:
description = "Internal Server Error";
break;
default:
description = "Unknown Status Code";
break;
}
return description;
}
console.log(`Status 201: ${getHTTPStatusDescription(201)}`);
console.log(`Status 400: ${getHTTPStatusDescription(400)}`);
console.log(`Status 999: ${getHTTPStatusDescription(999)}`);
break or return: Unless intentionally using fallthrough grouping, always end every case block with break or return.{} inside Cases: If declaring const or let variables inside a case, wrap the case body in { ... } curly braces to avoid scope collision with other cases.switch uses strict === matching without implicit coercion.What happens if you omit break; from case 200: when statusCode is 200?
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.