How to determine whether an object has a given property in JavaScript

Object has property:

If you are testing for properties that are on the object itself (not a part of its prototype chain) you can use .hasOwnProperty():

if (x.hasOwnProperty('y')) { 
  // ......
}

Object or its prototype has a property:

You can use the in operator to test for properties that are inherited as well.

if ('y' in x) {
  // ......
}

Leave a Comment