multiple expressions in one switch statement

12,967

Solution 1

You could do something like this:

var i = 1;
switch((i==1) + (Math.random(1)<0.3)*2) {
    case 0:
        //code block when neither is true
         break;
    case 1:
        //code block when only i == 1
         break;
    case 2:
        //code block when only random(1)<0.3
         break;
    case 3:
        //code block when both i==1 and random(1)<0.3
        break;
} 

... but it is not really the nicest code, and can easily lead to mistakes when one of the tested expressions is anything else than 0 or 1 (false or true).

It is better to use if ... else constructs to deal with this:

var i = 1;
var small = Math.random(1)<0.3;
if (i==1) {
    if (small) {
        //code block when both i==1 and random(1)<0.3
    } else {
        //code block when only i == 1
    }
} else if (small) {
    //code block when only random(1)<0.3
} else {
    //code block when neither is true
}

Solution 2

It's possible to write switch statements this way:

switch (true) {
  case a && b:
    // do smth
    break;
  case a && !b:
    // do other thing
    break;
}

The only thing you need to keep in mind is that && can return not only boolean, but rather any other value if e.g. 'a' (in code snippet above) resolves to some false value. If 'b' is string - then a && b, where a is false, shall return a string.
So when you use this pattern always ensure that the right side of && expression resolves to a boolean.

Share:
12,967
Roman
Author by

Roman

BY DAY: 8th grade bored excited student somewhere near Silicon Valley. BY NIGHT: Crazy processing.js programmer. Computer enthusiast. C learner. FUN: Entertaining my wonderment by picking up some electronics with Arduino and transistor logic gate adders. Still 13 now. Find me enjoying Elon Musk or IoT videos here and there.

Updated on June 04, 2022

Comments

  • Roman
    Roman almost 2 years

    It is my first time using the switch statement in Javascript. Is there a way to evaluate multiple conditions one switch statement, like so:

    var i = 1;
    switch(i && random(1)<0.3) {
        case (1):
            //code block
             break;
        case (2):
            //code block
    } 
    

    So that the code blocks would execute if both of the conditions were true?