Search code examples
javascriptoperatorsequalityinequality

Equality operator with multiple values in JavaScript


Is there a simple way to compare multiple values to a single value in Javascript ?

Like, instead of writing :

if (k != 2 && k != 3 && k!= 7 && k!12)

Writing something like :

if (k != {2,3,7,12})

Solution

  • You can use includes instead of multiple equality comparisons.

    if (![2,3,7,12].includes(k))
    

    That's boolean algebra:

    if (k != 2 && k != 3 && k!= 7 && k != 12)
    

    is equivalent to

    if (!(k == 2 || k == 3 || k == 7 || k == 12))
    

    and that's equivalent to

    if (![2,3,7,12].includes(k))