I read that : " The problem with a for...in loop is that it iterates through properties in the Prototype chain. When you loop through an object with the for...in loop, you need to check if the property belongs to the object. You can do this with hasOwnProperty." so what are the properties in the prototype chain and how for/in iterates through them?
I tried to run the code with and without hasOwnProperty
but it gives the same result
var myCar = {
color : "red" ,
type : "sedan" ,
price : "100,000" ,
model : "2020"
};
var prop ;
for (prop in myCar) {
if (myCar.hasOwnProperty(prop)){
console.log(prop + " : " + myCar[prop])
}
};
for (prop in myCar) {
console.log(prop + " : " + myCar[prop])
};
the result for both codes are : color : red type : sedan price : 100,000 model : 2020
for (prop in obj)enumerates through all object properties (own and inherited from prototype). In your case, the prototype doesn't have any property, so they're equivalent. The.hasOwnPropertyis a method returningtrueonly if the property is defined on current object, not inherited. You can read more here.