iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

RuleWhy it matters
Cases match with ===Type matters. case 1: won't match "1".
break exits the switchWithout it, execution "falls through" to the next case.
default is optionalIt runs when no case matches — convention is to put it last.
Cases can share code by omitting breakStack 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(); ;

Test yourself

Q1. Switch cases match using…
Q2. Without `break` at the end of a case…
Q3. Stacking case labels (no body between) means…

Discussion

Loading…