Quiz

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

Topics
JavaScript

TL;DR

Use the in operator when inherited properties should count, and Object.hasOwn() when only the object's own properties should count. Avoid calling obj.hasOwnProperty() directly because the object can shadow that method or have a null prototype.

const obj = { key: 'value' };
// Using the `in` operator
if ('key' in obj) {
console.log('Property exists');
}
// Checking only own properties
if (Object.hasOwn(obj, '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 legacy hasOwnProperty method checks if a property exists directly on the object, not in its prototype chain. Calling it directly is safe only when you know the object's prototype and properties are controlled.

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 Object.hasOwn()

  • The in operator checks for both own and inherited properties.
  • Object.hasOwn() 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(Object.hasOwn(childObj, 'inheritedKey')); // false
console.log('ownKey' in childObj); // true
console.log(Object.hasOwn(childObj, 'ownKey')); // true

Further reading

Exercícios

Verifique seu entendimento
Beta
Verifique seu entendimento Exercício
Verifique seu entendimento Exercício

What does this code log?

const prototype = { role: 'reader' };
const user = Object.create(prototype);
user.name = 'Ada';
console.log(
'role' in user,
Object.hasOwn(user, 'role'),
Object.hasOwn(user, 'name'),
);