0

Can I make a switch case that looks for a number in between a certain range? like 1-4 example:

 switch(3.43) {
      case '1,2,3,4,5' :
      console.log('its 3.43!')
      break;    
      case '6-10' :
      console.log('its not 3!')
      break;  
  }
nick
  • 1,226
  • 3
  • 21
  • 38

3 Answers3

3

Use if else

<script type="text/javascript">

function checkNumber () {
var n = //get value
var entered = "You entered a number between"; 

if (n >= 1 && n < 10)                   
  {alert(entered + " 0 and 10")}
else if (n >= 10 && n < 20)
  {alert(entered + " 9 and 20")}
else if (n >= 20 && n < 30)
  {alert(entered + " 19 and 30")}
else if (n >= 30 && n < 40)
  {alert(entered + " 29 and 40")}
else if (n >= 40 && n <= 100)
  {alert(entered + " 39 and 100")}
else if (n < 1 || n > 100)
  {alert("You entered a number less than 1 or greater than 100")}
else
  {alert("You did not enter a number!")}
}

</script>
Maddy
  • 907
  • 3
  • 10
  • 25
2

Just use a normal if statement:

var num = 3.43;
if (1 <= num && num <= 5) {
    console.log("Yay!");
} else if (6 <= num && num <= 10) {
    console.log("Aww.");
}

switch statements only allow for specific cases. It's possible to do ranges, but it's a bit hacky.

Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
1

Unfortunately not. Per MDN:

The program first looks for a case clause whose expression evaluates to the same value as the input expression (using strict comparison, ===) and then transfers control to that clause, executing the associated statements. If no matching case clause is found, the program looks for the optional default clause...

KJ Price
  • 5,774
  • 3
  • 21
  • 34