Own properties from hasOwnProperties, is ALL properties?

the lesson (eg name and numLegs are called own properties, because they are defined directly on the instance object. ) gives me the impression that hasOwnProperties returns only the properties inherited from the constructor, but that’s wrong, hu? it simply returns ALL properties currently on the object? (which in this lesson happens to be an instance of a contstructor)

function Bird(name) {
this.name = name;
this.numLegs = 2;

let canary = new Bird("Tweety");
canary = {...canary, nose: 'poynty'}

let ownProps = [];

for (let property in canary) {
if(canary.hasOwnProperty(property)) {

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36

Challenge: Understand Own Properties

Link to the challenge:

It returns all non-inherited properties on an object.

You have an object upon which you’ve defined three properties, so the code you have there prints three properties.

yeh, i’m forgetting about prototypes and inheritence. thanks

Yeah sorry, mistyped there as well, should have said it checks that a given non-inherited property exists on a given object and returns true if so (not “returns all non-inherited properties on an object”).

It doesn’t walk up the prototype chain, that’s the main thing. As opposed to “in”, which checks up the chain (hence why you use that if...hasOwnProperty check in the for..in loop).

Edit: Note also that hasOwnProperty has a replacement, hasOwn (which fixes a couple of small issues with hasOwnProperty), which works the same way

if (canary.hasOwn(property)) {
1 Like

i think hasOwn is brand new and doesn’t work yet on some browsers (jun 2022). (take that with a splash of noob sauce)

Only Internet Explorer, which is now dead (completely killed for good on June 15th), and Opera Mobile, which is barely used (hasn’t had releases for any platform for 12 months).

Everything else is supported, with the caveat that if a browser is locked to a specific old version may not work (applies w/r/t some companies’ IT policies, though becoming rarer because it opens the company up to security issues, policies are often now “lock to a specific browser that is kept updated”).

1 Like