Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : Check if object has properties [duplicate]

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){
like image 376
sebilasse Avatar asked Mar 29 '14 07:03

sebilasse


2 Answers

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.

like image 164
adeneo Avatar answered Nov 14 '22 19:11

adeneo


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

like image 39
nanobash Avatar answered Nov 14 '22 18:11

nanobash