References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript switch statement

Statement JavaScript All modern browsers Updated
Quick answer

The switch statement compares one value against several case values and runs the matching block. It's a clean alternative to a long if...else chain. Add break after each case to stop fall-through, and a default for the no-match case. It compares with strict equality (===).

Overview

switch takes a single value and checks it against a list of case values, running the block of the first one that matches. When you're branching on one variable with many possible fixed values — a status code, a menu choice, a day of the week — it's more readable than a tall stack of else ifs. Matching uses strict equality, the same as ===, so types must agree.

The famous trap is fall-through. After a matching case runs, execution keeps going into the next case unless you stop it with break. Forget the break and you'll run code from cases you didn't intend. This is occasionally used on purpose — stacking several case labels with no code between them lets them share a block — but an accidental missing break is a common bug.

Add a default case to handle anything that matches none of the others; it's the switch equivalent of a final else. For more complex conditions (ranges, multiple variables, truthiness), a if...else chain is still the better fit — switch is at its best comparing one value against discrete options.

Syntax

switch (value) {
  case "a":
    // runs if value === "a"
    break;
  case "b":
  case "c":
    // shared block for "b" or "c"
    break;
  default:
    // runs if nothing matched
}

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const day = new Date().getDay(); // 0-6
  let type;

  switch (day) {
    case 0:
    case 6:
      type = 'Weekend';
      break;
    default:
      type = 'Weekday';
  }

  document.getElementById('out').textContent = 'Today is a ' + type;
</script>

Best practices

  • Put a break after each case to prevent unintended fall-through.
  • Always include a default case to handle unexpected values.
  • Stack case labels deliberately when several should share one block.
  • Use a if...else chain instead for ranges or conditions on more than one value.

Frequently asked questions

Why do I need break in a switch statement?
Without break, execution falls through into the following cases. break stops after the matching case runs.
What does the default case do?
It runs when no case matches — the switch version of a final else.
When should I use switch instead of if...else?
When you're comparing one value against many discrete options. For ranges or multi-variable conditions, an if...else chain is clearer.
Does switch use == or ===?
Strict equality (===), so case 1 won't match the string "1".