The hasOwnProperty()
method returns true if the property is directly present in the object (not in its prototype chain). If an object is an Array, then the hasOwnProperty()
method can check if an index is available (not empty) in the array.
let user = {name : "Anitha", age : 25};console.log("The object is ", user);console.log("Cheking if name present in user", user.hasOwnProperty('name'));console.log("Cheking if age present in user", user.hasOwnProperty('age'));console.log("Cheking if salary present in user", user.hasOwnProperty('salary'));
in
vs. hasOwnProperty
The in
operator will check if the property is present, either directly in an object or in its prototype chain; whereas, the hasOwnProperty()
method only checks if the property is directly present in the object.
let emptyObj = {};console.log("checking if toString present in emptyObj with 'hasOwnProperty' method");console.log("emptyObj.hasOwnProperty('toString') => ", emptyObj.hasOwnProperty('toString'));console.log("\n---------\nchecking if toString present in emptyObj with 'in' method");console.log("'toString' in emptyObj => ", 'toString' in emptyObj);
When we use a for...in
loop, it loops through the object’s direct property and inherited properties. In this case, have used the hasOwnProperty
name:
let birds = { wings : true };let eagle = Object.create(birds);eagle.canFlyHigh = true;console.log("the eagle object is ", eagle);console.log("\n--------\nPrinting property of eagle using for...in ");for(prop in eagle){console.log(prop);}console.log("\n---------\nPrinting direct property of eagle - for...in and hasOwnProperty ");for(prop in eagle){if(birds.hasOwnProperty(prop)) {console.log(prop);} else{// inherited properties}}
If the user overrides hasOwnProperty
in the object, we can check if the object has a direct property by calling the hasOwnProperty
method on an empty object. If this
is our object, we need to check whether the property is present or not.
let alwaysFalse = {name : "test",hasOwnProperty : ()=> false};console.log(alwaysFalse.hasOwnProperty('name'));// To solve this , we can implement a custom functionfunction hasOwnProp(object, prop){return Object.prototype.hasOwnProperty.call(object, prop)}console.log(hasOwnProp(alwaysFalse, 'name'));