switch
Many exact cases.
When you compare one value against many exact options, like the day of the week, a long chain of else ifs gets repetitive. A switch statement is a neater way to write it.

- One value, many options
- Long else if chains
- switch is neater
Cases and break
Switch takes a value, and jumps to the case that matches it exactly. Break stops there, so it doesn't fall into the next case. Cases without a break share the same code. Default runs if nothing matches. Run it.
const day = "Saturday";
switch (day) {
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
case "Friday":
console.log("Almost the weekend");
break;
default:
console.log("A weekday");
}Weekend!
Forgetting break
The most common switch bug is forgetting a break. Then the code falls through, and runs the next case too. Switch uses strict equality, like three equals, so the number one won't match the string one.
| key | value |
|---|---|
| switch (value) | compare one value |
| case x: | an exact match |
| break | stop here |
| default | no match |
switch with numbers
Switch works with numbers too. Here we turn a month number into its season. Several cases share one block, by stacking them on top of each other. And because we return from a function, we don't need break, since return leaves the function straight away. Run it.
function season(month) {
switch (month) {
case 12: case 1: case 2: return "winter";
case 3: case 4: case 5: return "spring";
case 6: case 7: case 8: return "summer";
default: return "autumn";
}
}
console.log(season(1), season(4), season(7), season(10));winter spring summer autumn
Summary
Switch compares one value against exact cases. Remember break, and use default for no match. Next, loops, starting with for.
Key takeaways- case and break
- Shared cases
- default