Is there anyway to shorten something like this in Javascript: if (x == 1 || x == 2 || x == 3 || x == 4)
to something like if (x == (1 || 2 || 3 || 4))
?

- 151
- 1
- 3
-
If you're looking for syntax similar to what you posted, then no. You should consider that any roundabout way of shortening it will suffer a performance hit. – user113716 Feb 17 '11 at 17:51
-
Numbers were used as an example so using "if(x >0 && x < 5)" would not be useful if I am comparing strings. – John Feb 17 '11 at 18:46
5 Answers
You can use use Array.indexOf
[1,2,3,4].indexOf(x) !== -1
You can also use objects as some kind of hash map:
//Note: Keys will be coerced to strings so
// don't use this method if you are looking for an object or if you need
// to distinguish the number 1 from the string "1"
my_values = {1:true, 2:true, 3:true, 'foo':true}
my_values.hasOwnProperty('foo')
By the way, in most cases you should usi the "===" strict equality operator instead of the ==
operator. Comparison using "==" may do lots of complicated type coercion and you can get surprising results sometimes.

- 68,213
- 24
- 160
- 246
-
2Well *sometimes* "==" is useful, but you're probably right that "===" should be what a JavaScript programmer types automatically :-) – Pointy Feb 17 '11 at 17:49
-
1speaking about coercion, object initializer does it thrice :-P – Free Consulting Feb 17 '11 at 18:06
If your cases are not that simple to be expressed by this:
if (1 <= x && x <= 4)
You could use an array and indexOf
:
if ([1,2,3,4].indexOf(x) > -1)
Note that indexOf
might need to be re-implemented.

- 643,351
- 109
- 780
- 844
-
After removal of spaces, it's actually 1 character longer *(referring to `indexOf()`)*, but given a longer list of matches, it would be shorter. I guess it depends on actual code. – user113716 Feb 17 '11 at 17:44
Not without writing a function that takes an array as an input and returns true/false, or some sort of array search. It would be hard to maintain/other devs to read. And it would be significantly slower. So just stick with the semantically correct longer version.
Also a good way to see if anything can be shortened significantly is to run it through the close compiler and see what it comes out with.

- 61,249
- 84
- 283
- 456
-
I second this. It's often a good idea to encapsulate complex checks like this into a func to communicate the meaning better. – Juho Vepsäläinen Feb 17 '11 at 17:47
How about:
if (x > 0 && x < 5) {
}

- 27,113
- 11
- 60
- 86
-
I thought this, but then I realised John was presenting it as a simplified example not a case study so to speak. – Tom Gullen Feb 17 '11 at 17:40
You could write a function:
function isAny(x) {
for (var i = 1; i < arguments.length; ++i)
if (arguments[i] === x) return true;
return false;
}
Then you can say:
if (isAny(x, 1, 2, 3, 4)) { /* ... */ }
(Whether to use "===" or "==" would depend on the exact semantics you want.)

- 405,095
- 59
- 585
- 614