Combining multiple conditions into one of Javascript

How can I shorten this code? I want to return all values ​​except "abc" or "xyz" or "pqr"

return this.value != "abc" && this.value != "xyz"  && this.value != "pqr";

      

+2


source to share


2 answers


You can use an array:

return ["abc","xyz","pqr"].indexOf(this.value) == -1;

      



Or an object:

return !({"abc":1,"xyz":1,"pqr":1}).hasOwnProperty(this.value);

      

+1


source


The 2 most common ways are:

  • regular expression

    / ^ (a | xy | pqr). $ / Test (this.value)

  • searching object properties

    this.value in ({'abc': 1, 'xyz': 1, 'pqr': 1})



Note that a regex solution (# 1) will definitely be slower than a simple comparison (your version) or property lookup (# 2).

Also, remember that property lookups are not very reliable , as they can report false positives for any key that has the same name as any of the properties Object.prototype.*

(eg "toString", "valueOf", etc.)

+1


source







All Articles