Is Switch(true) {... Valid Javascript?
Solution 1:
This snippet is perfectly fine. It's just another way of expressing:
if (y < 20) {
// ...
} else if (y < 60) {
// ...
} else if ( y < 130) {
// ...
}
Solution 2:
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.
Solution 3:
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.
Solution 4:
The cases will get executed based on value of 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) {
// ...
}
Post a Comment for "Is Switch(true) {... Valid Javascript?"