65

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 !

user918967
  • 2,049
  • 4
  • 28
  • 43
  • 1
    What's in those variables? numbers? strings? – Madara's Ghost Feb 10 '12 at 21:37
  • 3
    25 case expressions?! That method will be huge. :-o Are you sure you need separate logic for all 25 states? – Mark Byers Feb 10 '12 at 21:40
  • If you have a lot of options, than simply concatenating them to something like `var1|var2` may be a very fast way. We'll need to see some examples of what you're doing though... – Michael Berkowski Feb 10 '12 at 21:40
  • 1
    There is probably a much better way to solve your problem. If you give us more info on the actual problem, you will probably get a lot of great suggestions :) – benekastah Feb 10 '12 at 21:42
  • Actually it is kinda complicated. What I am doing is using the ArcGIS Javascript API and I am displaying different maps based on where the sliders are stationed. What I really wanted to do is use the sliders to do some calculations *and* then display a map based on those calculations but that did not work out so hot. – user918967 Feb 10 '12 at 22:03

9 Answers9

54

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.

aabiro
  • 3,842
  • 2
  • 23
  • 36
33

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.

Héctor León
  • 2,210
  • 2
  • 23
  • 36
DashK
  • 2,640
  • 1
  • 22
  • 28
27
var var1 = "something";
var var2 = "something_else";
switch(var1 + "|" + var2) {
    case "something|something_else":
        ...
        break;
    case "something|...":
        break;
    case "...|...":
        break;
}

If you have 5 possibilities for each one you will get 25 cases.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • 60
    This, along with every other answer here, is horrible. The correct answer is to use `if`... – BlueRaja - Danny Pflughoeft Dec 17 '14 at 21:28
  • consider the case `var1 = "something|something_else";` and `var2 = "";` – Brian Hannay Jan 14 '15 at 19:58
  • @BrianHannay an extra `|` is inserted, the case would have to be `"something|something_else|"`. While it's not brilliant, my answer assumes you have complete control over `var1` and `var2`. If you assume you don't, what would your answer be? – Halcyon Jan 15 '15 at 11:32
  • @Halcyon I don't believe there is a very good way to do it, but nested switch statements (with variable options) could work. I just can't think of a case where the resulting action from the second slider (in OP's question) would depend on the value of the first. – Brian Hannay Jan 15 '15 at 19:47
  • 1
    @BlueRaja-DannyPflughoeft so true :) – Pranav A. Aug 20 '17 at 02:45
  • `encodeURIComponent(left) + "#" + encodeURIComponent(right)` (lord help me) – John Gietzen Jul 02 '20 at 01:56
14

First, JavaScript's switch is no faster than if/else (and sometimes much slower).

Second, the only way to use switch with multiple variables is to combine them into one primitive (string, number, etc) value:

var stateA = "foo";
var stateB = "bar";
switch (stateA + "-" + stateB) {
    case "foo-bar": ...
    ...
}

But, personally, I would rather see a set of if/else statements.

Edit: When all the values are integers, it appears that switch can out-perform if/else in Chrome. See the comments.

David Wolever
  • 148,955
  • 89
  • 346
  • 502
  • 1
    Repeat the same test, but with. say, 100 cases. The differences will become noticeable. – Rob W Feb 10 '12 at 21:41
  • Ah, on my browser, you seem to be correct when the value being switched over is an integer: http://jsperf.com/switch-ifelse-map/3 – David Wolever Feb 10 '12 at 22:03
  • doesn't necessarily have to be an integer. Your test case has to be modified though. Hashes are often the most efficient option out of `switch`, `else if` and `{}`. The overhead of creating a hash becomes negligible when checking often. It outperforms `switch` and `else if` in the long run. – Rob W Feb 10 '12 at 22:09
  • Oh, nuts, but it seems like my number test case was overwritten by my string test case. Anyway, numbers are faster, strings are identical. – David Wolever Feb 10 '12 at 22:10
  • Hi David, Thanks that is pretty awesome to be able to compare switching vs if/else and do it by integers and strings. Seems like switch and integer is fastest for FF9.01 – user918967 Feb 11 '12 at 03:26
  • 1
    Test links are now broken. – Obed Parlapiano Feb 23 '18 at 08:49
6

I don't believe a switch/case is any faster than a series of if/elseif's. They do the same thing, but if/elseif's you can check multiple variables. You cannot use a switch/case on more than one value.

kitti
  • 14,663
  • 31
  • 49
5

If the action of each combination is static, you could build a two-dimensional array:

var data = [
  [1,2,3,4,5],
  [6,7,8,9,10],
  [11,12,13,14,15],
  [16,17,18,19,20],
  [21,22,23,24,25]
];

The numbers in above example can be anything, such as string, array, etc. Fetching the value is now a one-liner (assuming sliders have a value range of [0,5):

var info = data[firstSliderValue][secondSliderValue];
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
4

Yeah, But not in a normal way. You will have to use switch as closure.

ex:-

function test(input1, input2) {
     switch (true) {
        case input1 > input2:
                    console.log(input1 + " is larger than " + input2);
                    break;
        case input1 < input2:
                    console.log(input2 + " is larger than " + input1);
        default:
                    console.log(input1 + " is equal to " + input2);
      }
   }
Parul
  • 119
  • 2
  • 3
4

I did it like this:

switch (valueA && valueB) {

case true && false:
console.log(‘valueA is true, valueB is false’)
break;

case ( true || false ) && true:
console.log(‘valueA is either true or false and valueB is true’)
break;

default:
void 0;
}
Mike K.
  • 637
  • 1
  • 5
  • 18
4

You could give each position on each slider a different binary value from 1 to 1000000000 and then work with the sum.

TecBrat
  • 3,643
  • 3
  • 28
  • 45