user2521439
user2521439

Reputation: 1425

Using multiple logical "or" operators

Other than using a switch statement (or writing if(x === 2 || x === 3 || x === 4) etc), is there any way to implement multiple "or" (||) operators?

E.g.:

if(x === 2 || 3)
    alert("Yes");

This alerts for every value of x

Upvotes: 1

Views: 163

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100630

Standard approach for large number of choices is to use dictionary/hash set/hash table depending on language.

For JavaScript both array and object would work:

var isPresent = [];  
isPresent[2] = true;
isPresent[43] = true;
if (isPresent[x])...

For small number of items Adam Rackis' answer with linear search is much more readable

 [2,3].indexOf(x)

Upvotes: 2

Adam Rackis
Adam Rackis

Reputation: 83376

The closest you can probably come is to do something like this:

if ([2,3].indexOf(x) > -1){
}

DOCS

Of course that will require a shim for IE 8 and below, if that's an issue for you.

Upvotes: 4

Related Questions