Quiz

How do you check if an object has a specific property?

Topics
JavaScript

TL;DR

To check if an object has a specific property, you can use the in operator or the hasOwnProperty method. The in operator checks for both own and inherited properties, while hasOwnProperty checks only for own properties. Since ES2022, Object.hasOwn() is the recommended way to check for own properties as it works safely even on objects created with Object.create(null).

const obj = { key: 'value' };
// Using the `in` operator
if ('key' in obj) {
console.log('Property exists');
}
// Using `hasOwnProperty`
if (obj.hasOwnProperty('key')) {
console.log('Property exists');
}

How do you check if an object has a specific property?

Using the in operator

The in operator checks if a property exists in an object, including properties in the object's prototype chain.

const obj = { key: 'value' };
if ('key' in obj) {
console.log('Property exists');
}

Using hasOwnProperty

The hasOwnProperty method checks if a property exists directly on the object, not in its prototype chain.

const obj = { key: 'value' };
if (obj.hasOwnProperty('key')) {
console.log('Property exists');
}

Using Object.hasOwn()

Object.hasOwn() (introduced in ES2022) is the recommended way to check for own properties. Unlike obj.hasOwnProperty(), it works on objects created with Object.create(null) (which have no prototype) and on objects that override the hasOwnProperty method.

const obj = { key: 'value' };
if (Object.hasOwn(obj, 'key')) {
console.log('Property exists');
}
// `Object.hasOwn` works even when there is no prototype
const bare = Object.create(null);
bare.key = 'value';
console.log(Object.hasOwn(bare, 'key')); // true
// bare.hasOwnProperty('key') would throw: bare.hasOwnProperty is not a function

Differences between in and hasOwnProperty

  • The in operator checks for both own and inherited properties.
  • The hasOwnProperty method checks only for own properties.

Example with inherited properties

const parentObj = { inheritedKey: 'inheritedValue' };
const childObj = Object.create(parentObj);
childObj.ownKey = 'ownValue';
console.log('inheritedKey' in childObj); // true
console.log(childObj.hasOwnProperty('inheritedKey')); // false
console.log('ownKey' in childObj); // true
console.log(childObj.hasOwnProperty('ownKey')); // true

Further reading

Edit on GitHub