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
- The
switchexpression is evaluated (day). - The
casewhose value matches is searched for (with===-style comparison). - Its code runs until a
breakis found. - If nothing matches, the
defaultblock 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.
switchshines with fixed and known values (days, menu options, order states). For ranges (grade >= 5) theif/else ifis 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");
}