Last updated

JavaScript Switch

Definition: A switch compares one value against many fixed options. It is often cleaner than a long else if chain.

Example 1 — a basic switch

let day = 3;
switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  default:
    console.log("Another day");
}

How it works

  • JavaScript compares the value against each case
  • On a match it runs that block
  • break stops it falling into the next case
  • default runs when nothing matches (like else)

Example 2 — the break gotcha

Leave out break and execution "falls through" into the next case — usually a bug:

let n = 1;
switch (n) {
  case 1:
    console.log("one");
    // no break -> falls through!
  case 2:
    console.log("two");
    break;
}

💡 Tip: use switch when comparing the same variable to many values; use if/else if for ranges and complex conditions.

Try it Yourself
Output

          
Ad · responsive