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