I don't understand an example

Hello, I’m wondering why there is an if statement like this

let ownProps = [];

for (let property in duck) {
  if(duck.hasOwnProperty(property)) {
    ownProps.push(property);
  }
}

console.log(ownProps); // prints [ "name", "numLegs" ]

when it could be done like this

let ownProps = [];

for (let property in duck) {
  
    ownProps.push(property);
  
}

console.log(ownProps); // prints [ "name", "numLegs" ]

Why should it be checked if duck has a property, when it is 100% sure that it has?

They work differently

This excertp is from documentation on for…in

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

[note there is written inherited]

Iterating over own properties only

If you only want to consider properties attached to the object itself, and not its prototypes, use getOwnPropertyNames() or perform a hasOwnProperty() check ( propertyIsEnumerable() can also be used). Alternatively, if you know there won’t be any outside code interference, you can extend built-in prototypes with a check method.

Could you perhaps simplify this? English is not my native language.

neither is mine, I don’t know synonims to use

If you have an object (child) that inherits some properties from another object (parent), a for..in will loop through both the properties on the child and those inherited from the parent.

Is it this challenge?

If so, one of the next challenges shows some example code, and the if statement might make more sense (because now there is an else as well).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.