0

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})
JS1
  • 631
  • 2
  • 7
  • 23

1 Answers1

2

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))
jabaa
  • 5,844
  • 3
  • 9
  • 30