Difference between prop in obj and obj.hasOwnProperty (prop) and obj [prop]?

Should I use one over the other? Does everyone use them better together? Thanks.

+7
source share
2 answers
  • prop in obj checks to see if the obj property has a property named prop , even if it is just inherited from the prototype.

  • obj.hasOwnProperty(prop) checks to see if obj itself has a property named prop ; it ignores properties inherited from prototypes.

  • obj[prop] gets the value of the prop property.

Use what is appropriate for what you are trying to accomplish

Note. In all three cases, prop must be a string.

+19
source

Just for an example:

 var animal = {"legs": 4}; var dog = {"barks" : true}; dog.__proto__ = animal; // JS inheritance (dog inherits from animal) 

now it 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 the dog had the β€œlegs” property, let's say 5 (hhmm spooky, which I know), so the β€œin” operator (β€œlegs” of the dog) will refer to the β€œlegs” property that is declared in the dog’s subject rather than inherited β€œlegs” that come from an animal’s object. eg:.

 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 
+1
source

All Articles