Javascript : Check if object has properties

51,167

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

FIDDLE

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

Share:
51,167

Related videos on Youtube

sebilasse
Author by

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, 2020

Comments

  • sebilasse
    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){