I recently came across code where a switch statement seemed reversed with the answer (boolean) in the switch and the expressions in the case. The code ran fine as intended b
It is valid.
The code
switch(f0()) {
case f1(): ..;
case f2(): ..;
default: dflt;
}
where fX()
represents an arbitrary expression (a function invocation is used to show forced evaluation) can be approximately re-written as
for (;;) { // for "break"
var _x = f0()
if (_x === f1()) { .. }
if (_x === f2()) { .. }
dflt;
break;
}
That is, the expression in the case
is evaluated and then compared with the expression in the switch
. (This is a sharp divergence from languages like C or Java that require constant values in the case
expressions.)
Of course, the break
will "exit the switch" - as opposed to the standard fall-through semantics - and as such, where true
is the expression supplied to switch
, the posted example is semantically equivalent to the if/else if
as shown by aefxx.