Switch Statements
When you have many conditions checking the same variable, switch is cleaner than a long if/else if chain. Switch compares a value against multiple cases and runs the matching code.
Switch vs if/else
- switch (value) { case X: ... break; } — Compares value against each case
- break — Stops execution. Without it, code 'falls through' to the next case
- default — Runs if no case matches (like the else in if/else)
- When to use — When checking one variable against many specific values (days, months, status codes)
- When NOT to use — When conditions are ranges (score >= 90) or complex logic. Use if/else instead
Switch Code
const day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week 💼");
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
console.log("Midweek grind 📊");
break;
case "Friday":
console.log("TGIF! 🎉");
break;
case "Saturday":
case "Sunday":
console.log("Weekend! 🏖️");
break;
default:
console.log("Invalid day");
}
// Real use case: HTTP status codes
const status = 404;
switch (status) {
case 200: console.log("Success ✅"); break;
case 301: console.log("Redirected ↗️"); break;
case 404: console.log("Not Found ❌"); break;
case 500: console.log("Server Error 🔥"); break;
default: console.log("Unknown status");
}Tip
Tip
Intentional fall-through in switch is useful when multiple cases share the same code. Group cases like: case 'Tuesday': case 'Wednesday': case 'Thursday': console.log('Midweek'). Add a comment // fall-through to show it's intentional.
Never swallow errors silently. Log, report, recover gracefully.
Common Mistake
Warning
Forgetting the break statement causes fall-through — execution continues into the next case even if it doesn't match. This is the #1 switch bug. Always add break after each case unless you intentionally want fall-through.
Practice Task
Note
Build a day-type classifier with switch: (1) Monday-Friday prints 'Weekday'. (2) Saturday-Sunday prints 'Weekend'. (3) Use fall-through for grouped days. (4) Add a default case for invalid input.
Quick Quiz
Key Takeaways
- When you have many conditions checking the same variable, switch is cleaner than a long if/else if chain.
- switch (value) { case X: ... break; } — Compares value against each case
- break — Stops execution. Without it, code 'falls through' to the next case
- default — Runs if no case matches (like the else in if/else)