Iterate Over All Properties. Clarification required

Iterate Over All Properties. Clarification required
0

#1

Hello fellow campers! Can someone please explain what this line from the example code below do?

for (let property in duck) {


let ownProps = [];
let prototypeProps = [];

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

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


Browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 OPR/56.0.3051.52.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/object-oriented-programming/iterate-over-all-properties


#2

This line iterate similar to for into an array. The difference is that instead of iterating over the indexes of an array, for in iterates over the properties of an object.

Example:

let obj = {
  name: 'camper',
   lastname:'bot',
  age: 5
  }

for (let property in obj) {
  if(obj.hasOwnProperty(property)) {
    ownProps.push(property);
  } else {
    prototypeProps.push(property);
  }
}

console.log(ownProps); // prints ['name', 'lastname', 'age']

#3

So it’s like a shortcut to iterate through all properties of an object? Only you don’t have to set up the whole counter thing like we do with usual for loops, this one is set to iterate through properties by default.
Thank you!


#4

Exactly! The for in statement iterates through all the properties of an object, (both own and prototype). The variable to iterate must be declared and not initialized.


#5

Now, the reason for the the duck.hasOwnProperty() check is, duck may be derived from another object. At the very least, it’s derived from javascript’s Object object. If we have created properties on our duck (with, for example, duck.breed = curlew; ), that is duck’s own property, and thus duck.hasOwnProperty("breed") would return true.

Properties that are on any ‘parent object’, like javascript’s Object, are not duck’s own. They are “inherited” (oversimplified, but the idea’s the same. Don’t shoot me.). Inherited properties are not this objects own properties, so .hasOwnProperty() will return false for these.