Skip to content

JavaScript switch case multiple arguments | Example code

  • by

Use the fall-through feature of the switch statement to use a switch case with multiple arguments in JavaScript. A matched case will run until a break (or the end of the switch statement) is found.

JavaScript switch case multiple arguments

In simple example code we have to define different cases without breaks in between like given below:

<!DOCTYPE html>
<html>
<body>
  <script type="text/javascript">
    var varName = "foo"

    switch (varName)
    {
     case "foo":
     case "bar":
     case "lop": 
     alert('Hey'+ " " + varName);
     break;

     default: 
     alert('Default case');
   }

 </script>

</body>
</html>

Output:

JavaScript switch case multiple arguments

Another example

This works in regular JavaScript:

function theTest(val) {
  var answer = "";
  switch( val ) {
    case 1: case 2: case 3:
      answer = "Low";
      break;
    case 4: case 5: case 6:
      answer = "Mid";
      break;
    case 7: case 8: case 9:
      answer = "High";
      break;
    default:
      answer = "Massive or Tiny?";
  }
  return answer;
}

theTest(9);

With strings

var color = "yellow";
var darkOrLight="";
switch(color) {
    case "yellow":case "pink":case "orange":
        darkOrLight = "Light";
        break;
    case "blue":case "purple":case "brown":
        darkOrLight = "Dark";
        break;
    default:
        darkOrLight = "Unknown";
}

Use a case/switch statement with two variables

This code executes the switch statement, pretty much just like if/else but looks cleaner. It will continue checking your variables in the case expressions.

switch (true) {

     case (var1 === true && var2 === true) :
       //do something
       break;
     case (var1 === false && var2 === false) :
       //do something
       break;

      default:

    }

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading