Switch on ranges of integers in JavaScript [duplicate] Switch on ranges of integers in JavaScript [duplicate] javascript javascript

Switch on ranges of integers in JavaScript [duplicate]


Here is another way I figured it out:

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


Incrementing on the answer by MarvinLabs to make it cleaner:

var 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;}

It is not necessary to check the lower end of the range because the break statements will cause execution to skip remaining cases, so by the time execution gets to checking e.g. (x < 9) we know the value must be 5 or greater.

Of course the output is only correct if the cases stay in the original order, and we assume integer values (as stated in the question) - technically the ranges are between 5 and 8.999999999999 or so since all numbers in js are actually double-precision floating point numbers.

If you want to be able to move the cases around, or find it more readable to have the full range visible in each case statement, just add a less-than-or-equal check for the lower range of each case:

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

Keep in mind that this adds an extra point of human error - someone may try to update a range, but forget to change it in both places, leaving an overlap or gap that is not covered. e.g. here the case of 8 will now not match anything when I just edit the case that used to match 8.

    case (x >= 5 && x < 8):        alert("between 5 and 7");        break;    case (x >= 9 && x < 12):        alert("between 9 and 11");        break;


    switch(this.dealer) {        case 1:        case 2:        case 3:        case 4:            // Do something.            break;        case 5:        case 6:        case 7:        case 8:            // Do something.            break;        default:            break;    }

If you don't like the succession of cases, simply go for if/else if/else statements.