JavaScript Object.hasOwnProperty()


The Object.hasOwnProperty() method checks if the object possesses the given property.

Example


hasOwnProperty() syntax

The syntax of the hasOwnProperty() method is:

obj.hasOwnProperty(prop)

Here, obj is the object in which we want to search for the property.

Being a static method, we need to access hasOwnProperty() using the class name Object.


hasOwnProperty() Parameters

The hasOwnProperty() method takes in:

  • prop - the String name or Symbol of the property to test.

hasOwnProperty() Return Value

The getPrototypeOf() method returns a Boolean value:

  • true - if the object possesses the specified property
  • false - if the object doesn't possess the specified property

Notes:

  • Unlike the in operator, this method does not check for a property in the object's prototype chain.
  • hasOwnProperty() returns true even if the value of the property is null or undefined.

Example : Javascript Object.hasOwnProperty()

In the above example, we have created an object obj with a single property id.

We then used the hasOwnProperty() method to check if obj has the id and name properties.

The output indicates that the object possesses id but doesn't possess the name property.

Finally, we used hasOwnProperty() to check if toString is defined in the object.

However, even though toString is a property of all objects in JavaScript, we still get false as an output.

This is because toString is an inherited property rather than a property that has been directly defined in the object itself.


Recommended Reading: