Lesson 17 +15 XP

JavaScript Switch

JavaScript Switch

The switch statement picks one of many blocks to run based on a value.

The switch syntax

switch (day) {
  case "Monday":
    console.log("Start of week");
    break;
  case "Friday":
    console.log("Almost weekend");
    break;
  case "Saturday":
  case "Sunday":
    console.log("Weekend!");
    break;
  default:
    console.log("Midweek");
}

How it works

  • The switch compares the value against each case.
  • When a case matches, that code runs.
  • break stops the switch from falling through to the next case.
  • default runs when nothing matches (like an else).

Fall through

If you forget break, execution continues into the next case. Sometimes this is used on purpose, like the Saturday/Sunday example above.

switch vs if...else

  • switch is clean for comparing one value against many fixed options.
  • if...else is better for ranges and complex conditions.

TL;DR

  • switch runs the matching case.
  • break stops fall through.
  • default handles no-match situations.
  • Use switch for many fixed-value comparisons.