Confused about Understand Own Properties, Javascript

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

Challenge: Understand Own Properties

Link to the challenge:

that’s the thing, it is not always true

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

1 Like

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.

1 Like

Then the exercise should be after we learn about prototype, ain’t it?

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.

Hello there,

What you are referencing is an object literal. What is being discussed is a class object (not all that different to an object literal, but in the case of inheritance, different). This is how you could loop through the internal prototypes of an object literal: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf

Hope this clarifies.

1 Like

I’ve just edited the code with that idea, although I called them ‘native’ constructors, XD

Yes, it clarifies a lot. Thanks.

probably you are right - do you want to report this as a bug?

depending on how near we are to new curriculum based project it may be worth fixing it