by mangeletti on 1/7/17, 3:34 PM with 2 comments
var x = 1;
switch (x) {
case 1:
console.log('case 1');
case 2:
console.log('case 2');
case 3:
console.log('case 3');
default:
console.log('default');
}
Before you raise your hand, yes I've intentionally omitted the break statements.And, the answer is:
case 1
case 2
case 3
default
The switch is designed to execute every case after the first match, which is the reason for placing a `break` after each case.My assumption was always that the `break` was to avoid wasting the interpreter's time on checking the remaining cases when you knew they'd all be non-matches, not that `break` was basically required.
This means that the switch statement itself is basically useless without `break`, unless each case is ordered in a 1[2,[3,[4]]] fashion (I imagine that's quite rare).
Is this just an artifact taken from C, or is there something else I'm overlooking?
by richardboegli on 1/7/17, 3:46 PM
by davelnewton on 1/7/17, 4:16 PM
Intentional fall-through isn't as rare as you seem to think, though--not useless at all.