Jaanus Jaanus - 1 year ago 76
Javascript Question

Switch on ranges of integers in JavaScript

I want to do something like this

switch (this.dealer) {
case 1-4:
// Do something.
break;
case 5-8:
// Do something.
break;
case 9-11:
// Do something.
break;
default:
break;
}


What is the right syntax for this? Is it possible in JavaScript?

So
this.dealer
is an integer, and if it's between those values, do something.

Answer Source

Here is another way I figured it out:

var x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x > 4 && x < 9):
        alert("between 5 and 8");
        break;
    case (x > 8 && x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download