Skip to content
Advertisement

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

How can I determine whether an object x has a defined property y, regardless of the value of x.y?

I’m currently using

if (typeof(x.y) !== 'undefined')

but that seems a bit clunky. Is there a better way?

Advertisement

Answer

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) {
  // ......
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement