Test for multiple cases in a switch, like an OR (||)
Asked Answered
P

7

329

How would you use a switch case when you need to test for a or b in the same case?

switch (pageid) {
  case "listing-page":
  case "home-page":
    alert("hello");
    break;
  case "details-page":
    alert("goodbye");
    break;
}
Parallax answered 28/6, 2011 at 21:57 Comment(3)
possible duplicate of using OR operator in javascript switch statement -- it's 100% your question ;)Francisfrancisca
I found using commas only 2 options allowed each case.Pepito
Does this answer your question? Switch statement for multiple cases in JavaScriptOrbital
B
791

You can use fall-through:

switch (pageid)
{
    case "listing-page":
    case "home-page":
        alert("hello");
        break;
    case "details-page":
        alert("goodbye");
        break;
}
Blaise answered 28/6, 2011 at 21:58 Comment(5)
I found this out before I posted the question, but thought it would be useful for the community since it's not well documented anywhere... thank you @SLaks for you're answer too.Parallax
Hi @Blaise I know this isn't the proper place for this, but you answered my last question correctly #21049505 would you like to repost your answer?Hydrolyze
I might as well clarify the point: Once a case has evaluated to true, that's it. No more cases are checked, just all the statements executed until the end: i.e. a "break;" instruction or if the switch is terminated.Inger
other examples here in MDN docsDecency
Linters often complain when using fall-through as the fall-through can happen due to lack of a break. The recommended approach would be to create a function that would be called by both casesThynne
T
148

Since the other answers explained how to do it without actually explaining why it works:

When the switch executes, it finds the first matching case statement and then executes each line of code after the switch until it hits either a break statement or the end of the switch (or a return statement to leave the entire containing function). When you deliberately omit the break so that code under the next case gets executed too that's called a fall-through. So for the OP's requirement:

switch (pageid) {
   case "listing-page":
   case "home-page":
      alert("hello");
      break;

   case "details-page":
      alert("goodbye");
      break;
} 

Forgetting to include break statements is a fairly common coding mistake and is the first thing you should look for if your switch isn't working the way you expected. For that reason some people like to put a comment in to say "fall through" to make it clear when break statements have been omitted on purpose. I do that in the following example since it is a bit more complicated and shows how some cases can include code to execute before they fall-through:

switch (someVar) {
   case 1:
      someFunction();
      alert("It was 1");
      // fall through
   case 2:
      alert("The 2 case");
      // fall through
   case 3:
      // fall through
   case 4:
      // fall through
   case 5:
      alert("The 5 case");
      // fall through
   case 6:
      alert("The 6 case");
      break;

   case 7:
      alert("Something else");
      break;

   case 8:
      // fall through
   default:
      alert("The end");
      break;
}

You can also (optionally) include a default case, which will be executed if none of the other cases match - if you don't include a default and no cases match then nothing happens. You can (optionally) fall through to the default case.

So in my second example if someVar is 1 it would call someFunction() and then you would see four alerts as it falls through multiple cases some of which have alerts under them. Is someVar is 3, 4 or 5 you'd see two alerts. If someVar is 7 you'd see "Something else" and if it is 8 or any other value you'd see "The end".

Tablet answered 29/6, 2011 at 0:32 Comment(2)
The //fall through comment make my phpstorm stop warning me about the fall-through switch statement, thanks :)Acklin
You can use return instead of break if the switch is in a function that you call to return some object: switch (action.type) { case ADD: { return newState; } case DELETE: { return newState; } default: { return state; } }Harem
A
18

You have to switch it!

switch (true) {
    case ( (pageid === "listing-page") || (pageid === ("home-page") ):
        alert("hello");
        break;
    case (pageid === "details-page"):
        alert("goodbye");
        break;
}
Achilles answered 15/12, 2015 at 16:44 Comment(2)
This method is very innovative :-) I like it for that. But, as it uses more characters than the classic "fall-through", it becomes lesser interesting :)Whoremaster
@Whoremaster the most weird and ironical that in another stackouverflow question such answer was totally downvoted. But nevertheless i support this answer and agree, that's good solution for flexible conditions.Carbo
P
16

You need to make two case labels.

Control will fall through from the first label to the second, so they'll both execute the same code.

Penneypenni answered 28/6, 2011 at 21:59 Comment(0)
B
4

Forget switch and break, lets play with if. And instead of asserting

if(pageid === "listing-page" || pageid === "home-page")

lets create several arrays with cases and check it with Array.prototype.includes()

var caseA = ["listing-page", "home-page"];
var caseB = ["details-page", "case04", "case05"];

if(caseA.includes(pageid)) {
    alert("hello");
}
else if (caseB.includes(pageid)) {
    alert("goodbye");
}
else {
    alert("there is no else case");
}
Bebeeru answered 6/5, 2017 at 21:59 Comment(1)
I think this is not the best solution, specially for perfomance. The .includes is way slower than a switch case, and thus, using if/else. It is best by using the switch case with fall-through.Karolekarolina
G
0

Cleaner way to do that 👌

if (["listing-page", "home-page"].indexOf(pageid) > -1)
    alert("hello");

else if (["exit-page", "logout-page"].indexOf(pageid) > -1)
    alert("Good bye");

You can do that for multiple values with the same result

Gingersnap answered 7/9, 2021 at 13:25 Comment(0)
V
-9

Use commas to separate case

switch (pageid)
{
    case "listing-page","home-page":
        alert("hello");
        break;
    case "details-page":
        alert("goodbye");
        break;
}
Varied answered 27/8, 2014 at 14:30 Comment(1)
The reason why this doesn't work is because case "listing-page","home-page": is equivalent to case "home-page": (because "listing-page","home-page" is just an expression evaluating to "home-page").Ruralize

© 2022 - 2024 — McMap. All rights reserved.