Javascript : Check if object has properties
Solution 1
They are almost equal, the difference is that hasOwnProperty
does not check down the prototype chain, while in
does.
An example
var test = function() {}
test.prototype.newProp = function() {}
var instance = new test();
instance.hasOwnProperty('newProp'); // false
'newProp' in instance // true
As noted, Object.hasOwnProperty
only returns "own properties", i.e. properties that are added directly, and not properties added to the prototype
.
Solution 2
Yes, there is difference. hasOwnProperty()
ignores properties and methods which are added with prototype
. I try to explain with examples. For instance if you have prototype of object
Object.prototype.something = function() {};
And let's say you have following object
var obj = {
"a" : "one",
"b" : "two"
};
And loop:
for ( var i in obj ) {
//if (obj.hasOwnProperty(i)) {
console.log(obj[i]);
//}
}
Without hasOwnProperty
it will output one two function()
, while with hasOwnProperty()
method only one two
See the differences between First and Second DEMOS
Related videos on Youtube
sebilasse
Sebastian Lasse is a photojournalist and developer based in Dortmund, Ruhr, germany. Sebastian Lasse Photography Explore high-quality reportage, daily events, portrait & public relations photography. Photos and writings are printed in magazines, newspapers, campaigns, books and business publications. A quick, discrete processing goes without saying. Sebastian Lasse New Media builds interactive journalistic solutions and is currently developing a new kind of cloud cms, redaktor.
Updated on December 07, 2020Comments
-
sebilasse over 3 years
There are several answers here how to check if a property exists in an object.
I was always using
if(myObj.hasOwnProperty('propName'))
but I wonder if there is any difference from
if('propName' in myObj){
-
Dunken about 10 yearswhy not just "if (myObj.propName)"?
-
Deepak Ingole about 10 years
-
sebilasse about 10 yearshey guys, thankyou - sorry, did not find the mentioned dup.
-