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
The syntax of switch statement is:
SwitchStatement : switch ( Expression ) CaseBlock CaseBlock : { CaseClauses(opt) } { CaseClauses(opt) DefaultClause CaseClauses(opt) } CaseClauses : CaseClause CaseClauses CaseClause CaseClause : case Expression : StatementList(opt) DefaultClause : default : StatementList(opt)
No where it says that switch expression or the case expression has to be a number, string, boolean or anything. true
is perfectly acceptable as a switch expression and y < 20
is perfectly acceptable as case expression. Keep in mind that comparison between switch expression and case expressions are made using ===
operator.
In the code you posted, the first true
case will be executed until break
is encountered or the switch block ends.
This snippet is perfectly fine. It's just another way of expressing:
if (y < 20) {
// ...
} else if (y < 60) {
// ...
} else if ( y < 130) {
// ...
}
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.
y
.Because the conditions depend on the value of y
. As said by aefxx, it is an other form of:
if (y < 20) {
// ...
} elseif (y < 60) {
// ...
} elseif ( y < 130) {
// ...
}
Yes, it's valid.
As in many "modern" languages, the switch
in Javascript is very far from the original int-based switch
from the C language, it only keeps the general semantics.
The switch clause, as normalized in ECMAScript, is explained here in details : http://www.ecma-international.org/ecma-262/5.1/#sec-12.11
Basically, the first case whose value is equal to the expression in switch(Expression)
is executed.
The main advantage over the obvious if else if
sequence is the ability to ommit the break
statement and execute more than one block. Note that, contrary to the old C switch, there is no real performance improvement and in this case it's neither more succinct nor more readable.