Skip to content

JavaScript switch case multiple conditions | Example code

  • by

You can use multiple conditions in the switch case same as using in JavaScript if statement.

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

You can do that but the switch statement will switch on the result of the expression you provide.

Given you have a logical and (&&) in your expression there are two possible outcomes defined by how && works.

  1. if the left-hand expression evaluates to true the expression will be equal to the evaluation of the second part.
  2. if the left-hand expression evaluates to false the whole expression will evaluate to false.

JavaScript switch case multiple conditions

Simple example codes multiple expressions in one switch statement.

<!DOCTYPE html>
<html>
<body>
  <script type="text/javascript">
    var pageid = "home-page";

    switch (true) {

      case ( (pageid === "listing-page") || (pageid === "home-page") ):
        alert("Hello Home");
        break;

        case (pageid === "details-page"):
        alert("Goodbye");
        break;
      }

    </script>

</body>
</html>

Output:

JavaScript switch case multiple conditions

Switch statement for multiple cases in JavaScript

If you are looking for multiple cases, not conditions then use the fall-through feature of the switch statement.

witch (varName)
{
   case "afshin":
   case "saeed":
   case "larry": 
       alert('Hey');
       break;

   default: 
       alert('Default case');
}

Do comment if you have any doubts or suggestions on this JS switch case topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *