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

Solution 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:

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:

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) {
}