Skip to content

JavaScript switch multiple cases | Example code

  • by

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

JavaScript switch with multiple cases

A simple example code makes multiple case labels.

<!DOCTYPE html>
<html>
  <body>
    <script>

      var varName = "larry"

      switch (varName)
      {
       case "afshin":
       case "saeed":
       case "larry": 
       alert('Hello' + " " + varName);

       break;

       default: 
       alert('Default case');
     }

   </script>

 </body>
 </html>

Output:

JavaScript switch multiple cases

More example

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

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