11

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

2
  • 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. Commented 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. Commented Feb 17, 2011 at 18:46

5 Answers 5

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Well sometimes "==" is useful, but you're probably right that "===" should be what a JavaScript programmer types automatically :-)
speaking about coercion, object initializer does it thrice :-P
2

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

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

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

I second this. It's often a good idea to encapsulate complex checks like this into a func to communicate the meaning better.
1

How about:

if (x > 0 && x < 5) {
} 

1 Comment

I thought this, but then I realised John was presenting it as a simplified example not a case study so to speak.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.