Search code examples
javascriptswitch-statementfall-through

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


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;
}

Solution

  • You can use fall-through:

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