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.
No, this is not possible. The closest you can get is:
But this very unwieldly.
For cases like this it's usually better just to use a
if
/else if
structure.If you are trying to do something fast, efficient and readable, use a standard if...then...else structure like this:
If you want to obfuscate it and make it awful (but small), try this:
BTW, the above code is a JavaScript if...then...else shorthand statement. It is a great example of how NOT to write code unless obfuscation or code minification is the goal. Be aware that code maintenance can be an issue if written this way. Very few people can easily read through it, if at all. The code size, however, is 50% smaller than the standard if...then...else without any loss of performance. This means that in larger codebases, minification like this can greatly speed code delivery across bandwidth constrained or high latency networks.
This, however, should not be considered a good answer. It is just an example of what CAN be done, not what SHOULD be done.
This does not require a switch statement. It is much clearer, more concise, and faster to simply use if else statements...
Speed test
I was curious about the overhead of using a switch instead of the simpler if...else..., so I put together a jsFiddle to examine it... http://jsfiddle.net/17x9w1eL/
Chrome: switch was around 70% slower than if else
Firefox: switch was around 5% slower than if else
IE: switch was around 5% slower than if else
Safari: switch was around 95% slower than if else
Notes:
Assigning to the local variable is optional, especially if your code is going to be automatically optimised later.
For numeric ranges, I like to use this kind of construction...
... because to me it reads closer to the way you would express a range in maths (1 <= d <= 11), and when I'm reading the code, I can read that as "if d is between 1 and 11".
Clearer
A few people have commented that they don't think this is clearer. It's certainly not less clear as the structure is close to identical to the switch option. The main reason it is clearer is that every part of it is readable and makes simple intuitive sense, whereas "switch (true)" is a rather meaningless line of code. Many coders, reading that in your script, are going to go "WTF does that mean?" and then have to look it up. It's a dirty hack, it's not intuitive, and it's not clear. If that's how you like to code, and no one else is ever going to have to deal with your code base, then go for it, otherwise, it's better just to use the constructs for what they are intended.