Search code examples
javascriptcomparison-operators

Concatenating comparisons in javascript


This is more out of curiosity but is it possible to concatenate comparisons in javascript?

example:

var foo = 'a',
    bar = 'b';
if (foo === ('a' || bar)) {
    console.log('yey');
}

as oposed to...

var foo = 'a',
    bar = 'b';
if (foo === 'a' || foo === bar)) {
    console.log('yey');
}

P.S: When you are comparing the same variable in several conditions, this could be very useful.


Solution

  • You can use Array.indexOf:

    if (["a", "b"].indexOf(foo) > -1) {
        console.log("yey");
    }
    

    Though this method is not supported by some old browsers, have a look at the compatibility issues in MDN -- there is an easy shim provided.

    Another way, suggested by @Pointy in the comments, is to check if property exists in object:

    if (foo in {a: 1, b: 1}) {  // or {a: 1, b: 1}[foo]
        console.log("yey");
    }