Object.hasOwn() Method – Check If an Object Owns a Property Directly
Whenever you use Object.hasOwn() on a JavaScript object, the method does the following:
- It checks if the object owns the specified property as its direct property—not as its inherited property.
- It returns true if the object has the specified property as its own property. Otherwise, it returns false.
Syntax of the Object.hasOwn()
Method
Object.hasOwn()
accepts two arguments. Here’s the syntax:
- The
obj
argument refers to the JavaScript object you want to test. - The
prop
argument is the name of the property you wish to find in the specified object.
Examples of the Object.hasOwn()
Method
Below are examples of the Object.hasOwn()
method.
Check if profile
has its own firstName
property
The snippet above returned true
because firstName
is one of the profile
object’s direct properties.
Check if profile
has its own companyName
property
The snippet above returned true
because companyName
is one of the profile
object’s own properties.
Check if profile
has its own website
property
The snippet above returned false
because website
is not part of the profile
object’s direct properties.
Check if profile
has its own valueOf
property
The snippet above returned false
because valueOf
is not part of the profile
object’s own properties—although it is one of its inherited properties.
Object.hasOwn
vs. Object.prototype.hasOwnProperty()
Developers prefer Object.hasOwn()
to the Object.prototype.hasOwnProperty()
method because hasOwn()
accepts the objects you create using Object.create(null)
.
For instance, consider the following code:
JavaScript threw an error because the hasOwnProperty()
method does not work with the objects you create using the Object.create(null)
method. However, hasOwn()
accepts such objects.
Here’s an example:
Object.hasOwn
vs. the in
Keyword
The Object.hasOwn()
method checks an object for its own (direct) properties only.
However, the in
keyword allows you to check an object for its direct (own) and indirect (inherited) properties.
For instance, consider the following code:
The snippet above returned false
because constructor
is not part of the profile
object’s direct properties.
Note that constructor
is one of the profile
object’s inherited properties, but hasOwn
finds only direct properties. You can, however, use the in
keyword to find inherited properties.
Here’s an example: