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.
Here is another way I figured it out:
If you don't like the succession of cases, simply go for
if/else if/else
statements.If you need check ranges you are probably better off with
if
andelse if
statements, like so:A switch could get large on bigger ranges.
A more readable version of the ternary might look like:
Incrementing on the answer by MarvinLabs to make it cleaner:
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:
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.