When you're comparing one value against a list of specific options, a long chain of else if can get repetitive:
if (day === "Monday") {
...
} else if (day === "Tuesday") {
...
} else if (day === "Wednesday") {
...
}
For this situation, JavaScript has the switch statement:
const day = "Saturday";
switch (day) {
case "Monday":
console.log("Ugh. Coffee, please. ☕");
break;
case "Friday":
console.log("Almost the weekend! 🎉");
break;
case "Saturday":
case "Sunday":
console.log("Weekend! Time to relax. 😎");
break;
default:
console.log("Just another day.");
}
It prints
Weekend! Time to relax. 😎
Here's how it works:
switch (day)says "let's look at the value ofday."- Each
caseis one possible value to compare against (using strict===comparison). - When a case matches, JavaScript runs the code under it...
- ...until it hits a
break, which jumps out of the wholeswitch. defaultis like the finalelse: it runs if no case matched.
Notice how "Saturday" and "Sunday" share the same code? When a case has no code and no break, JavaScript "falls through" to the next case. This lets you group several values together.
If you forget a break, JavaScript doesn't stop. It keeps running the code in the following cases too, even if they don't match!
const fruit = "apple";
switch (fruit) {
case "apple":
console.log("Apples are red.");
case "banana":
console.log("Bananas are yellow.");
case "grape":
console.log("Grapes are purple.");
}
It prints
Apples are red. Bananas are yellow. Grapes are purple.
All three printed! This is called fall-through, and when it happens by accident, it's a bug. Always end each case with break (unless you're deliberately grouping cases, like Saturday and Sunday above).
if/else or switch?
Use if / else if when... | Use switch when... |
|---|---|
You're checking ranges (score >= 80) | You're matching one value against exact options |
| Conditions involve different variables | You have lots of specific cases (days, menu choices, commands) |
Conditions combine && and || | Several values should share the same code |
Honestly? Lots of developers just use if/else if almost all the time. Both are fine. Use whichever makes your code easier to read.