Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

Should I use one over the other? Is using them all together better? Thanks.

like image 342
David G Avatar asked Sep 28 '11 02:09

David G


People also ask

What is the difference between in and hasOwnProperty?

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.

What's the difference between the in operator and the hasOwnProperty method in objects?

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.

Why do we use hasOwnProperty?

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.

What is object prototype hasOwnProperty?

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).


2 Answers

  • 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.

like image 104
SLaks Avatar answered Sep 28 '22 20:09

SLaks


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
like image 25
Mercury Avatar answered Sep 28 '22 19:09

Mercury