hasOwnProperty in JavaScript

The hasOwnProperty returns true if the property is its own property and not inherited.

Syntax of hasOwnProperty

Where prop is the name of the property to check.

In the example below, we define prop1 in the obj. Hence the hasOwnProperty returns true. But prop2 does not belong to obj, Hence it returns false.

Own vs inherited Property

The hasOwnProperty returns true only if the property is its own property. For Example, toString in the following code is the inherited property hence returns false.

The object must inherit from Object

The hasOwnProperty method belongs to the Object.prototype. Hence it works only our object inherits from it.

When we create an object using object literal or constructor function, it always inherits from the Object.

But, you can also create an object without settings it prototype as shown below. In that case hasOwnProperty will not work

In that case, we can use the call method to invoke the hasOwnProperty and passing the object as its this.

Overriding hasOwnProperty in the object

The JavaScript does not stop anyone from overriding the hasOwnProperty property down the prototype chain.

The code below declares the hasOwnProperty and always returns false. We can use the same workaround, we used in the previous section

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top