What is "hasOwnProperty"?


#1

I don't get what "hasOwnProperty" actually does. Here is an example from the Javascript course, exercise 29 of Introduction to Objects II. I didn't get it and just copied the answer from a fellow coder on the forum. Thanks for the help!

// what is this "Object.prototype" anyway...?
var prototypeType = typeof Object.prototype
console.log(prototypeType);

// now let's examine it!
var hasOwn = Object.prototype.hasOwnProperty("hasOwnProperty")
console.log(hasOwn);


#2

hasOwnProperty is a method, a property of Object.prototype by which we can query an object for a direct property. If it is not a direct property, then it is not an own property.

var me = {
    name: "Roy",
    age: "n/a"
}

console.log(me.hasOwnProperty('name'));    // true
console.log(me.hasOwnProperty('age'));     // true
console.log(me.hasOwnProperty('height'));  // false

#3

Not to spam, but to further illustrate,

var me = {
    name: "Roy",
    age: "n/a"
};

console.log(me.hasOwnProperty('name'));    // true
console.log(me.hasOwnProperty('age'));     // true
console.log(me.hasOwnProperty('height'));  // false

me.isSet = function(prop){
    return this.hasOwnProperty(prop) && this[prop];
};

console.log(me.isSet('name'));             // Roy
console.log(me.isSet('age'));              // n/a
console.log(me.isSet('height'));           // false

#4

Thanks, I understand now!