Skip to content

JavaScript switch case range | Example code

  • by

JavaScript switch-case statements can validate cases based on the range of values. Remember you need to have a boolean true value as a variable in the switch statement but not the variable to validate as in normal cases

JavaScript switch case range

Simple example code Switch on ranges of integers in JavaScript.

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

    var selIndex = 0;
    var val = 100;
    switch(true)
    {
      case ((val >= 1) && (val <= 10)):
      selIndex = 0;
      break;
      case ((val >= 11) && (val <= 100)):
      selIndex = 1;
      break;
      case ((val >= 101) && (val <= 1000)):
      selIndex = 2;
      break;
      case ((val >= 1001) && (val <= 10000)):
      selIndex = 3;
      break;

    }
    console.log(selIndex)
  </script>

</body>
</html>

Output:

JavaScript switch case range

Another example

const x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x < 9):
        alert("between 5 and 8");
        break;
    case (x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}

List each case

switch(myInterval){

    case 0:
    case 1:
    case 2:
        //doStuff();
        break;

    case 3:
    case 4:
    case 5:
    case 6:
        //doStuff();
        break;

    case 6:
    case 7:
        //doStuff();
        break;

    default:
        //doStuff();
}

If you know the range is going to be very high(for example 0-100) you can also do this, which is surely easier, cleaner, and simpler:

if (myInterval >= 0 && myInterval <= 20) {
    //doStuff();
} else if (myInterval > 20 && myInterval <= 60) {
    //doStuff();
} else if (myInterval > 60 && myInterval <= 70) {
    //doStuff();
} else /* it is greater than 70 */ {
    //doStuff();
}

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