🎓 A1Learner
🔍

JavaScript Switch

A switch statement compares one value against a list of cases. The block of the matching case runs.

Match a day

The value 3 matches the third case. Its line runs, and break ends the switch.

const 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");
}

Falling through

The first case has no break here. Both lines run, as the output shows.

const level = 1;
switch (level) {
  case 1:
    console.log("Start");
  case 2:
    console.log("Next");
    break;
  default:
    console.log("Other");
}

The default case

The value 9 matches no case here. The default block runs.

const day = 9;
switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  default:
    console.log("Unknown day");
}

Example

const grade = "B";
switch (grade) {
  case "A":
    console.log("Excellent work");
    break;
  case "B":
    console.log("Good work");
    break;
  case "C":
    console.log("Fair work");
    break;
  default:
    console.log("No grade recorded");
}

Key points

  • Each case names one value to match.
  • switch matches values with strict equality.
  • The break statement ends a case block.
  • break stops the switch from falling into the next case.
  • A case without break runs the next case as well.
  • default covers values that match no case.

In this example, the grade B matches the second case. That case logs its line and break ends the switch. No other case runs.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does break do inside a switch statement?