DevPath · Learn to code ESPTEN

Conditionals

The switch structure

switch

When you compare the same variable against a bunch of specific values, the else if ladder gets long and tiring to read. The switch is like a switchboard: "depending on the value that comes in, go to this door". Same result, much tidier on the eyes:

const day = "monday";

switch (day) {
  case "saturday":
  case "sunday":
    console.log("Weekend 🎉");
    break;
  case "monday":
    console.log("The week begins");
    break;
  default:
    console.log("Weekday");
}

How it works

  1. The switch expression is evaluated (day).
  2. The case whose value matches is searched for (with ===-style comparison).
  3. Its code runs until a break is found.
  4. If nothing matches, the default block runs.

⚠️ CLASSIC TRAP: the missing break!

Without break, execution does not stop at its case: it spills over and keeps running the next one, and the next... (this is the "fall-through" effect). Sometimes it is used on purpose, like when we group "saturday" and "sunday" above, but forgetting it by accident is one of the sneakiest bugs out there: the code "almost" works and you go nuts figuring out why. Get into the habit of typing the break at the same time as the case.

switch shines with fixed and known values (days, menu options, order states). For ranges (grade >= 5) the if/else if is still your best friend.

You can now branch: your program picks paths. The next superpower is to repeat without copy-pasting the same thing a thousand times. Those are loops, and they are waiting for you in the next module.

Examples

Order status based on its code

const code = 2;
switch (code) {
  case 1:
    console.log("Active");
    break;
  case 2:
    console.log("Inactive");
    break;
  default:
    console.log("Unknown");
}
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Truthy/falsy and the ternary operatorView the module →