Object.hasOwnProperty

Could someone please explain what I am doing wrong here? I am the Object.hasOwnProperty to check to see if object o and u has the property in question. However, when I ran these objects, one gives me true and the other one is false. I am going crazy trying to figure this out.

object o:

Blockquote
let o = { top: 25, middle:‘mid’};
o.hasOwnProperty(‘top’);
true
Blockquote

block u:

Blockquote
let u = [
{f: ‘Harry’,
l: 15,
}
]
u.hasOwnProperty(‘f’);
false
Blockquote

The first is an object with two properties top and middle.

The second is an array with a single element. The element is an object with two properties f and l.

The hasOwnProperty can only be used with objects and not arrays.

Thank you for your clear explanation.

I mean technically arrays do have hasOwnProperty on them.

[].hasOwnProperty('length')
// true

But that obviously won’t help you check for properties on any object elements inside it.

I am a beginner and not sure how to check this hasOwnProperty thing. I have to figure out how sometime in the future. Thank you for the response.

You already did it in the first example.

You are supposed to be using it on “normal” objects. For an array with objects inside it, you have to access the objects like any other element.

const arr = [{ name: 'John'}];
arr[0].hasOwnProperty('name'); // true

As an aside and not to confuse you.

You can use hasOwnProperty on an array because it’s actually an object as you can also tell by the length property on it.

const arr = []
arr.newProp = 'weird but it works'
console.log(arr.newProp) // 'weird but it works'
arr.hasOwnProperty('newProp'); // true

You can do the same with a function.

function canIHazProps() {
  // do something
}

canIHazProps.yes = 'you can have a property'
console.log(canIHazProps.yes) // 'you can have a property'
canIHazProps.hasOwnProperty('yes'); // true

So basically anything with a property on it can be checked using hasOwnProperty but it really only makes sense for “normal” objects.