Else check being met after if check

Tell us what’s happening:

  **Your code so far**

function Dog(name) {
this.name = name;
}

Dog.prototype.numLegs = 4;

let beagle = new Dog("Snoopy");

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

// Only change code below this line
for (let property in beagle) {
if(beagle.hasOwnProperty(property)) {
  ownProps.push(property);
} else {
  prototypeProps.push(property);
}
}

Challenge: Iterate Over All Properties

Link to the challenge:

How is this adding both the own properties and prototype properties to the array? Shouldn’t it stop at the if check since it is met? Why is the else block also being executed?

I guess I’m confused by the question.

This is the output I’m getting:

console.log(ownProps)
// [ 'name' ]
console.log(prototypeProps)
// [ 'numLegs' ]

which is what I expect.

Are you asking why else is ever being called? Only one is called on each iteration of the for loop, but the loop iterates twice. For example, if I log from your code:

for (let property in beagle) {
  console.log('property', property);
  if(beagle.hasOwnProperty(property)) {
    console.log('adding to ownProps');
    ownProps.push(property);
  } else {
    console.log('adding to prototypeProps');
    prototypeProps.push(property);
  }
}

I get:

property name
adding to ownProps
property numLegs
adding to prototypeProps

So, it goes through the loop twice. The first time it finds that “name” is an “own prop” so the if gets fired. On the second iteration, it finds that “numLegs” is not so the else gets fired.

I think proper indenting/formatting would help - that’s a good habit to get into.

1 Like