Warm tip: This article is reproduced from stackoverflow.com, please click
if-statement javascript

How to check if a variable equals one of two values if a clean manner in JS

发布于 2020-03-28 23:13:23

To check if x variable is equal to 1 or 2, i would do normally something like:

if (x === 1 || x === 2){
   // ....
}

but this can get in some cases very cumbersome.

Edit :I'm working right now on this and writing the fonction name every time i think can be done in a cleaner manner:

if (
      this.getNotificationStatus() === 'denied' ||
      this.getNotificationStatus() === 'blocked'
    )

Is there any other lighter way to write this?

THANKS

Questioner
B. Mohammad
Viewed
70
technophyle 2020-01-31 17:30

You could do:

if ([1, 2].includes(x)) {
  // ....
}

Or:

if ([1, 2].indexOf(x) > -1) {
  // ....
}

Or:

switch (x) {
  case 1:
  case 2:
    // ....
    break;
  default:
}

I don't think they're "lighter" than your solution though.