The switch Statement

Grade 4, page 8 of 11. A two-minute read.

When you're comparing one value against a list of specific options, a long chain of else if can get repetitive:

JavaScript
if (day === "Monday") {
  ...
} else if (day === "Tuesday") {
  ...
} else if (day === "Wednesday") {
  ...
}

For this situation, JavaScript has the switch statement:

JavaScript
const day = "Saturday";

switch (day) {
  case "Monday":
    console.log("Ugh. Coffee, please. ☕");
    break;
  case "Friday":
    console.log("Almost the weekend! 🎉");
    break;
  case "Saturday":
  case "Sunday":
    console.log("Weekend! Time to relax. 😎");
    break;
  default:
    console.log("Just another day.");
}

It prints

Weekend! Time to relax. 😎

Here's how it works:

  • switch (day) says "let's look at the value of day."
  • Each case is one possible value to compare against (using strict === comparison).
  • When a case matches, JavaScript runs the code under it...
  • ...until it hits a break, which jumps out of the whole switch.
  • default is like the final else: it runs if no case matched.

Notice how "Saturday" and "Sunday" share the same code? When a case has no code and no break, JavaScript "falls through" to the next case. This lets you group several values together.

Watch outForgetting break

If you forget a break, JavaScript doesn't stop. It keeps running the code in the following cases too, even if they don't match!

JavaScriptHas a bug
const fruit = "apple";

switch (fruit) {
  case "apple":
    console.log("Apples are red.");
  case "banana":
    console.log("Bananas are yellow.");
  case "grape":
    console.log("Grapes are purple.");
}

It prints

Apples are red.
Bananas are yellow.
Grapes are purple.

All three printed! This is called fall-through, and when it happens by accident, it's a bug. Always end each case with break (unless you're deliberately grouping cases, like Saturday and Sunday above).

if/else or switch?

Use if / else if when...Use switch when...
You're checking ranges (score >= 80)You're matching one value against exact options
Conditions involve different variablesYou have lots of specific cases (days, menu choices, commands)
Conditions combine && and ||Several values should share the same code

Honestly? Lots of developers just use if/else if almost all the time. Both are fine. Use whichever makes your code easier to read.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning