2.3 — else-if chains & switch
One fork gives you two roads. Real decisions often need more: grade an exam, route a support ticket, price by age group. Two tools today: chaining forks with else if, and a purpose-built ladder called switch.
switch comes with a famous trapdoor, fall-through, that once helped take down a national phone network. Really.
let grade = 87;
if (grade >= 90) {
console.log("A");
} else if (grade >= 80) {
console.log("B");
} else if (grade >= 70) {
console.log("C");
} else {
console.log("Try again");
}An else-if chain is a corridor of gates, checked strictly top-down. grade is 87 — walk with it: gate one asks >= 90?…
The deeper story, with the real names for things — this part is what turns “I saw it” into “I can explain it.”
Precision notes: an else-if chain is not a special syntax — it’s literally an else whose branch contains another if, stacked. That’s why exactly one branch ever runs.
switch compares with strict equality (===), so case "200" will never match the number 200 — a coercion-free zone, which is exactly why we like it.
default can sit anywhere in the ladder but belongs at the bottom by convention, and yes — it falls through too if unbroken.
Fun fact: on January 15, 1990, AT&T’s long-distance phone network collapsed for nine hours. Over 60 million calls failed. The root cause: a single misplaced break in a switch statement — in C, the language JavaScript borrowed switch (and its fall-through) from. One keyword, one wrong rung of the ladder, a national outage. It remains one of the most-cited examples of why tiny control-flow details deserve tests. Languages designed after C (like Swift and Go) made break the default.
✏️ Quick check 1
n can be any number. How many of them make bigPrize() run? Type the count — 0 if none.
if (n > 10) { smallPrize(); }
else if (n > 100) { bigPrize(); }✏️ Quick check 2
x is "a". How many numbers print? Type the count.
switch (x) {
case "a": console.log(1);
case "b": console.log(2); break;
case "c": console.log(3);
}✏️ Quick check 3
status holds the NUMBER 200. Which branch runs? Type its label.
switch (status) {
case "200": ok(); break;
default: huh();
}One day, you will read a code review comment like this. Later, you will write them:
if (score >= 40) { pass(); }else if (score >= 90) { topGrade(); } ← dead. can never run
score >= 90 first.Reviewers catch dead gates fast. Phase 10 makes reviewing part of your job.
🗣️ Now teach it back
Explain to a friend: how does an else-if chain decide which branch runs (and why does gate ORDER matter), and what is switch fall-through — feature and footgun?
Write it as if your friend is sitting next to you. Saved to your journal — future-you will use these notes to teach others.