Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorten JS if or statement [duplicate]

Tags:

javascript

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)) ?

like image 354
John Avatar asked Feb 17 '11 17:02

John


2 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.

like image 133
hugomg Avatar answered Oct 02 '22 21:10

hugomg


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.

like image 45
Gumbo Avatar answered Oct 02 '22 22:10

Gumbo