Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is switch(true) {... valid javascript?

Tags:

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; } 
like image 719
PrimeLens Avatar asked Jan 02 '13 08:01

PrimeLens


People also ask

Can I use switch true?

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.

Can we use switch in JavaScript?

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.

Does switch use == or ===?

In answer to your question, it's === .

Can you put if statements in switch statements JavaScript?

Yes, it is perfectly valid.


2 Answers

This snippet is perfectly fine. It's just another way of expressing:

if (y < 20) {     // ... } else if (y < 60) {     // ... } else if ( y < 130) {     // ... } 
like image 82
aefxx Avatar answered Sep 23 '22 12:09

aefxx


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.

like image 30
Denys Séguret Avatar answered Sep 23 '22 12:09

Denys Séguret