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){
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With