27

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){
sebilasse
  • 4,278
  • 2
  • 37
  • 36

2 Answers2

45

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.

adeneo
  • 312,895
  • 29
  • 395
  • 388
4

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

nanobash
  • 5,419
  • 7
  • 38
  • 56