Leo Messi
Leo Messi

Reputation: 6166

Multiple checks into one in JavaScript

I know that this may sound stupid but I was wondering if this code could be written in a shorter version:

if (this.myVeryLongName.aRandomProperty === 'property_1' || this.myVeryLongName.aRandomProperty === 'property_1' ||  this.myVeryLongName.aRandomProperty === 'property_1') {
     //do something
}

maybe something like this:

if (this.myVeryLongName.aRandomProperty === ('property_1' || 'property_1' ||  'property_1')) {
    //do something
}

Is any way to make it short and still have same functionality?

Upvotes: 0

Views: 67

Answers (3)

melpomene
melpomene

Reputation: 85767

There's a variety of ways to do this:

  • ['property_1','property_2','property_3'].includes( this.myVeryLongName.aRandomProperty )
    

    (ES 2016)

  • ['property_1','property_2','property_3'].indexOf( this.myVeryLongName.aRandomProperty ) !== -1
    

    (ES 5)

  • /^(?:property_1|property_2|property_3)$/.test( this.myVeryLongName.aRandomProperty )
    

    (Any JS version)

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Potentially even better option (than the one I posted in a comment)

switch(this.myVeryLongName.aRandomProperty) {
case 'property_1':
case 'property_2':
case 'property_3':
  doSomethingHere();
  break;
// if you have more cases, add them here!
}

Notice how this is much more easily readable, and extendable in future if needs change.

Upvotes: 1

Eddie
Eddie

Reputation: 26844

You can make an array and use includes, like:

if ( ['property_1','property_2','property_3'].includes( this.myVeryLongName.aRandomProperty ) ) {
    //do something
}

Doc: includes

Upvotes: 2

Related Questions