I have (ab)used a switch
statement like this:
const foo = figureOutWhatFooIs()
console.log(foo) // 'bar'
switch (foo) {
case 'bar':
console.log('foo = bar')
case 'baz':
console.log('foo = baz')
}
i.e. no break
's and no default
I discovered that even when foo = 'bar'
, the baz
case (and incidentally the last case) also executes.
I'm not surprised that the last case was checked but I am surprised that it executed. Thoughts? Thanks!
Checking is done at the start of switch
statement, not during running case
statements.
The case
clause works similar to labels and goto
/JUMP
statements in other languages such as C++1 and Assembly2, which means case 'bar':
is nothing more than a label that can be used to jump execution to it, but does nothing logical in itself.
So, when a case
clause matches, JavaScript jumps you to that label, and then runs all statements one by one, ignoring any other case
clauses because they're simply labels.
But of course, if there's any break
statement along the way, it'll exit switch
.
The main reason switch statement does not break by default could be so that it's easier to match multiple conditions like this:
switch (color) {
case 'red':
case 'orange':
case 'blue':
console.log('Colorful!');
break;
case 'black':
case 'white':
case 'gray':
console.log('Black & white!');
break;
default:
console.log('What color is that??');
}
1 https://en.cppreference.com/w/cpp/language/goto
2 https://www.tutorialspoint.com/assembly_programming/assembly_conditions.htm