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 but I'm concerned about cross browser. Is it valid javascript?
switch(true) { case (y < 20): // break; case (y < 60): // break; case (y < 130): // break; }
You probably know that the switch statement allows matching an expression (the switch ) against different values (the case ), so using switch(true) may seem absurd: Well, that's not true. You can match against values as well as expressions.
The switch statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions. Use switch to select one of many blocks of code to be executed. This is the perfect solution for long, nested if/else statements.
In answer to your question, it's === .
Yes, it is perfectly valid.
This snippet is perfectly fine. It's just another way of expressing:
if (y < 20) { // ... } else if (y < 60) { // ... } else if ( 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With