Case Fall-Through Behavior
What You'll Learn: How execution flows through multiple case blocks when you forget (or intentionally omit) the break statement.
The Fall-Through Phenomenon
In a switch statement, once JavaScript finds a matching case, it executes that block's code. But here's the catch: unless you explicitly use break, execution doesn't stop—it "falls through" into the next case block, and the next, until it hits a break or the end of the switch.
Think of it like a row of dominoes: knocking over the matching domino causes all the ones after it to fall too, unless you place a barrier (break) to stop the chain.
How It Works
let fruit = 'apple';
switch (fruit) {
case 'apple':
console.log('Red fruit'); // This runs
case 'banana':
console.log('Yellow fruit'); // This ALSO runs!
case 'grape':
console.log('Purple fruit'); // This runs too!
break;
default:
console.log('Unknown fruit');
}
// Output:
// Red fruit
// Yellow fruit
// Purple fruit
Even though fruit is 'apple', all three console.log statements execute because there's no break after the first two cases.
Intentional Fall-Through
Sometimes this behavior is useful when multiple cases should trigger the same code:
let day = 'Saturday';
switch (day) {
case 'Saturday':
case 'Sunday':
console.log('Weekend!');
break;
default:
console.log('Weekday');
}
// Output: Weekend!
Key Takeaway: Without break, execution continues into subsequent case blocks regardless of whether they match—this is fall-through behavior, which can be a bug or a feature depending on your intent.