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
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']
1 Like
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!
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.
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.