It is recommended to always use hasOwnProperty, but in many cases this is not needed. For example consider the following code:
var object = JSON.parse(somejsontext);
for(var prop in object) {
console.log(object[prop]);
}
I know in this case that prop
is part of the object, it is explict define by the for..in
.
But according to MOZ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty we should use it to avoid iterating over non-enumarable props, with this example:
var buz = {
fog: 'stack'
};
for (var name in buz) {
if (buz.hasOwnProperty(name)) {
console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]);
}
else {
console.log(name); // toString or something else
}
}
But testing this code actually, never goes to the else.
So when does make sense the use of hasOwnProperty
?
UPDATE: Considering the choosen answer, we can safetly avoid the use of hasOwnProperty in this cases:
- Object
js has not been extended by any javascript library or by our code
- Object
is a simple code that we have control on