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 !
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.
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.
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.
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