Reputation: 6166
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
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
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