Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a case/switch statement with two variables?

I am a newbie when it comes to JavaScript and it was my understanding that using one SWITCH/CASE statements is faster than a whole bunch of IF statements.

However, I want to use a SWITCH/CASE statement with two variables.

My web app has two sliders, each of which have five states. I want the behavior to be based on the states of these two variables. Obviously that is a whole heck of a lot of IF/THEN statements.

One way I thought about doing it was concatenating the two variables into one and then I could SWITCH/CASE that.

Is there a better way of accomplishing a SWITCH/CASE using two variables ?

Thanks !

like image 776
user918967 Avatar asked Feb 10 '12 21:02

user918967


People also ask

Can we use two variables in switch case?

Yes as other state. You can have only one expression but that expression can have multiple variables. Although, for readability, we recommend put a simple expression in the switch.

Can we use two variables in switch case in Java?

No. The argument for the switch must be an expression with evaluates to a single value. In Java the argument must be byte, short, char, int, their corresponding wrapper types, Strings or Enum Types.


1 Answers

Yes you can also do:

    switch (true) {       case (var1 === true && var2 === true) :        //do something        break;      case (var1 === false && var2 === false) :        //do something        break;        default:      } 

This will always execute the switch, pretty much just like if/else but looks cleaner. Just continue checking your variables in the case expressions.

like image 165
aabiro Avatar answered Oct 04 '22 14:10

aabiro