multiple expressions in one switch statement

Roman picture Roman · Jul 24, 2016 · Viewed 10.2k times · Source

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?

Answer

Ilya_S picture Ilya_S · Jul 24, 2016

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.