Should I use one over the other? Is using them all together better? Thanks.
For inherited properties, in will return true . hasOwnProperty , as the name implies, will check if a property is owned by itself, and ignores the inherited properties.
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.
JavaScript | hasOwnProperty() Method The hasOwnProperty() method in JavaScript is used to check whether the object has the specified property as its own property. This is useful for checking if the object has inherited the property rather than being it's own.
prototype. hasOwnProperty() The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
prop in obj
checks whether obj
has a property named prop
at all, even if it's just inherited from a prototype.
obj.hasOwnProperty(prop)
checks whether obj
itself holds a property named prop
; it ignores properties inherited from prototypes.
obj[prop]
gets the value of the prop
property.
Use whichever one is appropriate for what you're trying to accomplish
Note: In all three cases, prop
must be a string.
Just to give an example for this:
var animal = {"legs": 4};
var dog = {"barks" : true};
dog.__proto__ = animal; // JS inheritance (dog inherits from animal)
now this means that:
console.log("legs" in dog); // TRUE - due to JS inheritance and since 'in' key looks into inherited prototypes
console.log(dog.hasOwnProperty("legs")); // FALSE
console.log(dog.hasOwnProperty("barks")); //TRUE
prints
true
false
true
Note one more thing: If dog had "legs" property of lets say 5 (hhmm spooky i know), so the 'in' operator ("legs" in dog) will refer to the "legs" property which is declared in the dog object and not the inherited "legs" which comes from animal object. e.g.:
var animal = {"legs": 4};
var dog1 = {"barks": true};
var dog2 = {"barks": true, "legs": 5};
dog1.__proto__ = animal;
dog2.__proto__ = animal;
console.log(dog1.legs);
console.log(dog2.legs);
console.log("legs" in dog2) // 'in' refer to the un-inherited "legs" of dog2
prints
4
5
true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With