I'm trying to understand the goal of using hasOwnProperty()
check when iterating through object keys. As I know, the iteration will be executed for every object property (not more, not less) in both cases: with hasOwnProperty()
or without. For example, in code below results with hasOwnProperty()
check and without are the same:
const obj = {
prop1: [],
prop2: {},
prop3: "",
prop4: 0,
prop5: null,
prop6: undefined
}
const resultWithHasOwnProperty = [];
const resultWithoutHasOwnProperty = [];
for(key in obj) {
if(obj.hasOwnProperty(key)) {
resultWithHasOwnProperty.push(obj[key])
}
}
for(key in obj) {
resultWithoutHasOwnProperty.push(obj[key])
}
console.log("Result WITH hasOwnProperty check: ", resultWithHasOwnProperty);
console.log("Result WITHOUT hasOwnProperty check: ", resultWithoutHasOwnProperty);
So my question is: why and when should we use hasOwnProperty()
check?
I'll rephrase my question: without hasOwnProperty()
check we will always iterate through all existing properties anyway?
Notice, this question is not really a duplicate.