AI Hints
Home›JavaScript Tutorial›More Decisions
JavaScript · Lesson 24 of 138

switch

Many exact cases.

⏱ 2 min read▶ Video at 28:43🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

When you compare one value against many exact options, like the day of the week, a long chain of else ifs gets repetitive. A switch statement is a neater way to write it.

switch
From the video: switch
  • One value, many options
  • Long else if chains
  • switch is neater

Cases and break

Switch takes a value, and jumps to the case that matches it exactly. Break stops there, so it doesn't fall into the next case. Cases without a break share the same code. Default runs if nothing matches. Run it.

app.jsjavascript
const day = "Saturday";

switch (day) {
  case "Saturday":
  case "Sunday":
    console.log("Weekend!");
    break;
  case "Friday":
    console.log("Almost the weekend");
    break;
  default:
    console.log("A weekday");
}
Output
Weekend!

Forgetting break

The most common switch bug is forgetting a break. Then the code falls through, and runs the next case too. Switch uses strict equality, like three equals, so the number one won't match the string one.

keyvalue
switch (value)compare one value
case x:an exact match
breakstop here
defaultno match

switch with numbers

Switch works with numbers too. Here we turn a month number into its season. Several cases share one block, by stacking them on top of each other. And because we return from a function, we don't need break, since return leaves the function straight away. Run it.

app.jsjavascript
function season(month) {
  switch (month) {
    case 12: case 1: case 2: return "winter";
    case 3: case 4: case 5: return "spring";
    case 6: case 7: case 8: return "summer";
    default: return "autumn";
  }
}

console.log(season(1), season(4), season(7), season(10));
Output
winter spring summer autumn

Summary

Switch compares one value against exact cases. Remember break, and use default for no match. Next, loops, starting with for.

Key takeaways
  • case and break
  • Shared cases
  • default
Next up: for Loops — repeat with a counter