One value, many exact matches
When you compare one variable against a list of exact values, a chain of else if (day === ...) gets repetitive. switch is built for that shape:
const day = "sat"; switch (day) { case "sat": case "sun": console.log("Weekend"); break; case "mon": console.log("Back to work"); break; default: console.log("Midweek"); }
Three rules:
- Matching uses strict
===comparison. breakends the case. Without it, execution falls through into the next case. Stacking two case labels (like"sat"and"sun"above) uses that fall-through on purpose to share one body.defaultruns when nothing matched, like a finalelse.
Modern Python got match in 3.10, which plays a similar role.
Code exercise · javascript
Run it, then change day to "mon" and "wed" and run again to see the other branches. Try deleting the first break to watch fall-through happen.
Code exercise · javascript
Your turn. Write a switch on light: green prints Go, yellow prints Slow down, red prints Stop, and anything else prints Broken light. With light set to yellow it should print Slow down.
Quiz
What happens if you forget break at the end of a matching case?