How to Use Object.hasOwn in JavaScript: Syntax and Examples
Use
Object.hasOwn(object, property) to check if an object has a specific own property. It returns true if the property exists directly on the object, otherwise false. This method is a modern and safer alternative to hasOwnProperty.Syntax
The syntax for Object.hasOwn is simple:
object: The object you want to check.property: The name of the property you want to check for, as a string or symbol.
The method returns true if the property exists directly on the object (not inherited), otherwise false.
javascript
Object.hasOwn(object, property)Example
This example shows how to use Object.hasOwn to check if an object has a specific property:
javascript
const car = { brand: 'Toyota', year: 2020 }; console.log(Object.hasOwn(car, 'brand')); // true console.log(Object.hasOwn(car, 'color')); // false // Checking inherited property const parent = { wheels: 4 }; const child = Object.create(parent); child.doors = 2; console.log(Object.hasOwn(child, 'doors')); // true console.log(Object.hasOwn(child, 'wheels')); // false (inherited, not own)
Output
true
false
true
false
Common Pitfalls
Common mistakes when checking properties include:
- Using
inoperator which checks inherited properties too. - Using
hasOwnPropertydirectly on objects that might not have it (e.g., objects created withObject.create(null)).
Object.hasOwn avoids these issues by being a static method on Object and always safe to use.
javascript
const obj = Object.create(null); obj.key = 'value'; // Wrong: obj.hasOwnProperty might not exist // console.log(obj.hasOwnProperty('key')); // Error // Right: use Object.hasOwn console.log(Object.hasOwn(obj, 'key')); // true
Output
true
Quick Reference
| Method | Description | Returns |
|---|---|---|
| Object.hasOwn(object, property) | Checks if property is own property of object | true or false |
| object.hasOwnProperty(property) | Checks if property is own property (may fail if method missing) | true or false |
| property in object | Checks if property exists anywhere in object (own or inherited) | true or false |
Key Takeaways
Use Object.hasOwn(object, property) to safely check own properties.
It returns true only if the property exists directly on the object.
Avoid using hasOwnProperty on objects that may lack it, like Object.create(null).
The in operator checks inherited properties too, so it is not the same.
Object.hasOwn is a modern, reliable alternative introduced in recent JavaScript versions.