JavaScript ยท Chapter 30 of 55

JavaScript Switch Statement

The `switch` statement compares a value against multiple possible cases, offering a cleaner alternative to long if/else-if chains when checking one variable against many exact values.

Each `case` uses strict comparison (`===`), and you should include `break` after each case to prevent 'fall-through' into the next case.

Structure

`switch(value) { case a: ...; break; case b: ...; break; default: ...; }` runs the matching case block, or default if none match.

Fall-through

Omitting `break` causes execution to continue into the next case โ€” sometimes intentional, but usually a bug.

Example 1 (javascript)
let day = "Mon";
switch (day) {
  case "Mon":
    console.log("Start of week");
    break;
  case "Fri":
    console.log("Almost weekend");
    break;
  default:
    console.log("Midweek");
}
Output
Start of week

The case matching 'Mon' runs, then break exits the switch.

Example 2 (javascript)
let x = 2;
switch (x) {
  case 1:
  case 2:
    console.log("One or two");
    break;
  default:
    console.log("Other");
}
Output
One or two

Grouped cases (no break between 1 and 2) share the same block.

Key points

  • switch compares one value against multiple cases using ===.
  • `break` prevents fall-through to the next case.
  • `default` runs when no case matches.
  • Grouped cases without break can share the same logic block.
๐Ÿ’ก Note: Missing a break is one of the most common switch statement bugs โ€” always double check.

๐Ÿ“ Quick Quiz

1. What comparison does switch use for cases?

2. What does `break` do inside a case?

3. What runs when no case matches?