323

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;
}
Andres
  • 5,002
  • 6
  • 31
  • 34
  • 4
    possible duplicate of [using OR operator in javascript switch statement](http://stackoverflow.com/questions/6476994/using-or-operator-in-javascript-switch-statement) -- it's 100% your question ;) – Felix Kling Jun 28 '11 at 22:02
  • I found using commas only 2 options allowed each case. – Agus Widiarsa I Made Oct 17 '18 at 11:41
  • Does this answer your question? [Switch statement for multiple cases in JavaScript](https://stackoverflow.com/questions/13207927/switch-statement-for-multiple-cases-in-javascript) – AncientSwordRage Oct 27 '21 at 14:04

7 Answers7

771

You can use fall-through:

switch (pageid)
{
    case "listing-page":
    case "home-page":
        alert("hello");
        break;
    case "details-page":
        alert("goodbye");
        break;
}
Community
  • 1
  • 1
kei
  • 20,157
  • 2
  • 35
  • 62
  • 4
    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. – Andres Jun 29 '11 at 14:40
  • Hi @kei I know this isn't the proper place for this, but you answered my last question correctly http://stackoverflow.com/questions/21049005/jquery-animate-background-color-not-animating?noredirect=1#comment31647804_21049005 would you like to repost your answer? – Leon Gaban Jan 10 '14 at 16:28
  • 1
    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. – BeauCielBleu Dec 22 '14 at 09:19
  • 1
    other examples [here in MDN docs](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Statements/switch) – Luca Reghellin Jun 24 '15 at 09:46
  • 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 cases – Va5ili5 Jun 05 '22 at 20:17
145

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".

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • 4
    The //fall through comment make my phpstorm stop warning me about the fall-through switch statement, thanks :) – Getz Jul 17 '13 at 08:29
  • 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; } } – Dominika Feb 19 '19 at 21:20
17

You have to switch it!

switch (true) {
    case ( (pageid === "listing-page") || (pageid === ("home-page") ):
        alert("hello");
        break;
    case (pageid === "details-page"):
        alert("goodbye");
        break;
}
Stefano Favero
  • 331
  • 3
  • 6
  • 1
    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 :) – AlexLaforge Sep 11 '18 at 05:20
  • 1
    @AlexLaforge 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. – Alexey Nikonov Jun 16 '19 at 08:15
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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
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");
}
khex
  • 2,778
  • 6
  • 32
  • 56
  • 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. – Frederiko Ribeiro Sep 02 '20 at 11:02
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

Abraham
  • 12,140
  • 4
  • 56
  • 92
-9

Use commas to separate case

switch (pageid)
{
    case "listing-page","home-page":
        alert("hello");
        break;
    case "details-page":
        alert("goodbye");
        break;
}
Dinesh
  • 2,744
  • 1
  • 12
  • 12
  • 2
    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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) evaluating to `"home-page"`). – Simon Alling Aug 10 '21 at 14:37