Object Oriented Programming: Understand Own Properties

Hi,

I had a doubt about the challenge. Why do we need to check whether the object canary has the property if we are iterating through its properties as shown in the example?

Your code so far


function Bird(name) {
  this.name = name;
  this.numLegs = 2;
}

let canary = new Bird("Tweety");
let ownProps = [];
// Add your code below this line

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

The following for loop implementation gives the same result:

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

Am I missing something?

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

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

Got the reason a couple of exercises down.

Hi,
It would seem that way but if you are not sure of the prototype chain you often will need to filter out the inherited properties of the prototype(s). (Depends on what you want to include)

If there was a Bird.prototype then the situation would be different.

Here’s an example

var triangle = {a: 1, b: 2, c: 3};

function ColoredTriangle() {
  this.color = 'red';
}

ColoredTriangle.prototype = triangle;

var obj = new ColoredTriangle();

// filtered
for (const prop in obj) {
  if (obj.hasOwnProperty(prop)) {
    console.log(`obj.${prop} = ${obj[prop]}`);
  } 
}
// Output: obj.color = red


//unfiltered
for (const prop in obj) {
    console.log(`obj.${prop} = ${obj[prop]}`);
}
// Output: obj.color = red
// obj.a = 1
// obj.b = 2
// obj.c = 3
  • example pinched from MDN very last example
2 Likes

Thank you, I understood the reason when I got to the prototype exercises. I should have been patient with my query.

function Bird(name) {
this.name = name;
this.numLegs = 2;
}

let canary = new Bird(“Tweety”);
let ownProps = [];
// Add your code below this line

for(let property in canary) {
if (canary.hasOwnProperty(property)) {
ownProps.push(property);
}
}
I just wrote this and it worked…Weird…