The hasOwnProperty returns true if the property is its own property and not inherited.
Table of Contents
Syntax of hasOwnProperty
1 2 3 | object.hasOwnProperty(prop) |
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.
1 2 3 4 5 6 7 8 | const obj = { prop1: '1' }; obj.hasOwnProperty('prop1'); // true obj.hasOwnProperty('prop2'); // false. Does not exists |
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.
1 2 3 4 5 6 7 | var str = new String("Hello") console.log(str.toString()) //Works console.log(str.hasOwnProperty('toString')) //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
1 2 3 4 5 6 | newObj = Object.create(null) newObj.prop1=""; newObj.hasOwnProperty('prop1') //Uncaught TypeError: newObj.hasOwnProperty is not a function |
In that case, we can use the call
method to invoke the hasOwnProperty
and passing the object as its this
.
1 2 3 4 5 6 | newObj = Object.create(null) newObj.prop1=""; console.log(({}).hasOwnProperty.call(newObj,"prop1")) //true |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | const obj = { prop1: '1', hasOwnProperty() { return false } }; //uses the hasOwnProperty declared in the obj console.log(obj.hasOwnProperty('prop1')); // false //Work around using the call method console.log(({}).hasOwnProperty.call(obj,"prop1")) //true |
Read More