Course outline · 0% complete

0/29 lessons0%

Course overview →

switch

lesson 3-2 · ~8 min · 8/29

One value, many exact matches

When you compare one variable against a list of exact values, a chain of else if (day === ...) gets repetitive. switch is built for that shape:

const day = "sat";

switch (day) {
  case "sat":
  case "sun":
    console.log("Weekend");
    break;
  case "mon":
    console.log("Back to work");
    break;
  default:
    console.log("Midweek");
}

Three rules:

  1. Matching uses strict === comparison.
  2. break ends the case. Without it, execution falls through into the next case. Stacking two case labels (like "sat" and "sun" above) uses that fall-through on purpose to share one body.
  3. default runs when nothing matched, like a final else.

Modern Python got match in 3.10, which plays a similar role.

Code exercise · javascript

Run it, then change day to "mon" and "wed" and run again to see the other branches. Try deleting the first break to watch fall-through happen.

Code exercise · javascript

Your turn. Write a switch on light: green prints Go, yellow prints Slow down, red prints Stop, and anything else prints Broken light. With light set to yellow it should print Slow down.

Quiz

What happens if you forget break at the end of a matching case?