JS1
JS1

Reputation: 757

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

Upvotes: 0

Views: 505

Answers (1)

jabaa
jabaa

Reputation: 6810

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

Upvotes: 2

Related Questions