Object. hasOwn()
Checks whether an object has its own property with the given name.
- Returns
trueorfalse.- Changes the original
- No
Example
#const profile = { name: 'Mia', bio: undefined }
console.log(Object.hasOwn(profile, 'bio'))
console.log(Object.hasOwn(profile, 'toString'))
console.log('toString' in profile)Definition and usage
#The Object.hasOwn(obj, key) method returns true if the object has a property with that name directly on it, not inherited from the prototype. It’s a more modern and safer equivalent of obj.hasOwnProperty(key).
It differs from the in operator, which also checks inherited properties. For example, "toString" in {} returns true, while Object.hasOwn({}, "toString") returns false.
It also works on objects without a prototype (created with Object.create(null)), where the hasOwnProperty method doesn’t exist at all.
Syntax
#Object.hasOwn(obj, prop)Parameters
#obj
object
The object being checked.prop
string or symbol
The property name.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Checking with
if (obj.field)can’t tell a missing field apart from a value of0,"", orundefined.Object.hasOwn()can. - In new code, replace
hasOwnPropertywithObject.hasOwn().
Related entries
#Spotted a mistake or missing an example? Write to us.