'JavaScript: Simple way to check if variable is equal to one of two or more values? [duplicate]

Is there an easier way to determine if a variable is equal to a range of values, such as:

if x === 5 || 6 

rather than something obtuse like:

if x === 5 || x === 6

?



Solution 1:[1]

You can stash your values inside an array and check whether the variable exists in the array by using [].indexOf:

if([5, 6].indexOf(x) > -1) {
  // ...
}

If -1 is returned then the variable doesn't exist in the array.

Solution 2:[2]

Depends on what sort of test you're performing. If you've got static strings, this is very easy to check via regular expressions:

if (/^[56ab]$/.test(item)) {
//-or-
if (/^(foo|bar|baz|fizz|buzz)$/.test(item)) {
    doStuff();
} else {
    doOtherStuff();
}

If you've got a small set of values (string or number), you can use a switch:

switch (item) {
case 1:
case 2:
case 3:
    doStuff();
    break;
default:
    doOtherStuff();
    break;
}

If you've got a long list of values, you should probably use an array with ~arr.indexOf(item), or arr.contains(item):

vals = [1,3,18,3902,...];
if (~vals.indexOf(item)) {
    doStuff();
} else {
    doOtherStuff();
}

Unfortunately Array.prototype.indexOf isn't supported in some browsers. Fortunately a polyfill is available. If you're going through the trouble of polyfilling Array.prototype.indexOf, you might as well add Array.prototype.contains.

Depending on how you're associating data, you could store a dynamic list of strings within an object as a map to other relevant information:

var map = {
    foo: bar,
    fizz: buzz
}
if (item in map) {
//-or-
if (map.hasOwnProperty(item)) {
    doStuff(map[item]);
} else {
    doOtherStuff();
}

in will check the entire prototype chain while Object.prototype.hasOwnProperty will only check the object, so be aware that they are different.

Solution 3:[3]

It's perfectly fine. If you have a longer list of values, perhaps you can use the following instead:

if ([5,6,7,8].indexOf(x) > -1) {
}

Solution 4:[4]

Yes. You can use your own function. This example uses .some:

var foo = [ 5, 6 ].some(function(val) {
     return val === x;
   });

foo; // true

Solution 5:[5]

This is what I've decided to use:

Object.prototype.isin = function() {
    for(var i = arguments.length; i--;) {
        var a = arguments[i];
        if(a.constructor === Array) {
            for(var j = a.length; j--;)
                if(a[j] == this) return true;
        }
        else if(a == this) return true;
    }
    return false;
}

You would use it like this:

var fav   = 'pear',
    fruit = ['apple', 'banana', 'orange', 'pear'],
    plu   = [4152, 4231, 3030, 4409];

if (fav.isin(fruit, plu, 'eggs', 'cheese')) {
    //do something cool
}

The advantages are:

  • it works in IE < 9;
  • it reads naturally from left to right;
  • you can feed it arrays or separate values.

If you don't want to allow type coercion (indexOf does not), change the two == to ===. As it stands:

fav = "4231";
plu.indexOf(fav) //-1
fav.isin(plu)    //true

Solution 6:[6]

no, there might be a few tricks that are case specific but in general i write code like this:

if (someVariable === 1 ||
    someVariable === 2 ||
    someVariable === 7 ||
    someVariable === 12 ||
    someVariable === 14 ||
    someVariable === 19) {

    doStuff();
    moreStuff();

} else {
    differentStuff();
}

Solution 7:[7]

The simple answer is no. You can use a switch statement, which is easier to read if you are comparing a lot of string values, but using it for two values wouldn't look any better.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roy
Solution 2 Community
Solution 3 João Silva
Solution 4 David G
Solution 5 Greg Perham
Solution 6 orlp
Solution 7 monitorjbl