How do you check if an object has a specific property?
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` operatorif ('key' in obj) {console.log('Property exists');}// Checking only own propertiesif (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 prototypeconst 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
inoperator 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); // trueconsole.log(Object.hasOwn(childObj, 'inheritedKey')); // falseconsole.log('ownKey' in childObj); // trueconsole.log(Object.hasOwn(childObj, 'ownKey')); // true
Further reading
- MDN Web Docs: in operator
- MDN Web Docs: Object.prototype.hasOwnProperty
- MDN Web Docs: Object.hasOwn()