How do you check if an object has a specific property?
Topics
JAVASCRIPT
在GitHub上编辑
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.
const obj = { key: 'value' };// Using the `in` operatorif ('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');}
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); // trueconsole.log(childObj.hasOwnProperty('inheritedKey')); // falseconsole.log('ownKey' in childObj); // trueconsole.log(childObj.hasOwnProperty('ownKey')); // true