JS Switch
switch picks one branch from a list of candidate values. It's a flatter alternative to a long if/else if chain.
The shape
JS
switch (status) {
case "open":
open();
break;
case "closed":
case "expired": // ← multiple cases fall through to the same code
close();
break;
case "pending":
queue();
break;
default:
log("unknown status");
}
Key rules
| Rule | Why it matters |
|---|---|
Cases match with === | Type matters. case 1: won't match "1". |
break exits the switch | Without it, execution "falls through" to the next case. |
default is optional | It runs when no case matches — convention is to put it last. |
Cases can share code by omitting break | Stack labels on top of each other deliberately, as in the example. |
Switch on true — pattern-matching pattern
JS
switch (true) {
case xp >= 1000: title = "Ninja"; break;
case xp >= 500: title = "Coder"; break;
case xp >= 100: title = "Rookie"; break;
default: title = "Newcomer";
}
Tip: For mapping a key to a value, an object literal is often cleaner:
const title = { 1000: "Ninja", 500: "Coder" }[level] ?? "Newcomer";Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Switch!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Exit the current switch case so execution does not fall through.
case 'open': open();
;
Five letters.
Discussion
Loading…