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)) ?
-
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– user1137162011-02-17 17:51:50 +00:00Commented Feb 17, 2011 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– John2011-02-17 18:46:04 +00:00Commented Feb 17, 2011 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.
2 Comments
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.
1 Comment
indexOf()), but given a longer list of matches, it would be shorter. I guess it depends on actual code.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.
1 Comment
How about:
if (x > 0 && x < 5) {
}