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

user918967 picture user918967 · Feb 10, 2012 · Viewed 137.4k times · Source

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 !

Answer

DashK picture DashK · Feb 10, 2012

How about a bitwise operator? Instead of strings, you're dealing with "enums", which looks more "elegant."

// Declare slider's state "enum"
var SliderOne = {
    A: 1,
    B: 2,
    C: 4,
    D: 8,
    E: 16
};

var SliderTwo = {
    A: 32,
    B: 64,
    C: 128,
    D: 256,
    E: 512
};

// Set state
var s1 = SliderOne.A,
    s2 = SliderTwo.B;

// Switch state
switch (s1 | s2) {
    case SliderOne.A | SliderTwo.A :
    case SliderOne.A | SliderTwo.C :
        // Logic when State #1 is A, and State #2 is either A or C
        break;
    case SliderOne.B | SliderTwo.C :
        // Logic when State #1 is B, and State #2 is C
        break;
    case SliderOne.E | SliderTwo.E :
    default:
        // Logic when State #1 is E, and State #2 is E or
        // none of above match
        break;


}

I however agree with others, 25 cases in a switch-case logic is not too pretty, and if-else might, in some cases, "look" better. Anyway.