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?
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.