What’s happening:
I’m completing a few exercises. In the introduction to Understand Own Properties there is this code:
Your code so far
let ownProps = [];
for (let property in duck) {
if(duck.hasOwnProperty(property)) {
ownProps.push(property);
}}
I wonder why would that be preferred to:
for (let property in duck) {ownProps.push(duck)}
In my perspective, either we shouldn’t be testing (conditional) for the same object, it should be a different one; or we could remove the conditional at all, since it will always be true.
Help?
Update
There are a few more things I’d like to add
If the point of the exercise is to recognize prototype properties, it should be after we learn prototype, not before.
In any case, if we console.log (properties) prototype properties never get logged out, so I assume that hasOwnProperty is still pointless if this were the case. (correction for this: it is only for ‘native’ constructors like String, Array… that nothing gets logged out, for constructors we build, it does).
the for…in loop iterate over all the properties, also those in the prototype chain hasOwnProperty instead returns true only for the property that are directly in the object
Think of it this way, since it’s OOP you’re doing, what if that object inherited property from another object? Own property is an object’s “own” property, not an inherited property.
By inherited you mean prototype? Because if I run a for loop, the prototype properties never get logged out, it only iterates over the own properties. Example:
let myObject = {hello:
"julia", hello2: "selectiveduplicate"}
for (let property in myObject) {
console.log(property)
}
It logs out hello and hello2 and not any property from the Object constructor.
Edit: I’ve just realized that prototypes from ‘native’ objects are not console logged but the ones we manually create are. Sorry for the confusion, and thanks.