What is property in hasOwnProperty in JavaScript?

FLY picture FLY · Feb 22, 2012 · Viewed 163.5k times · Source

Consider:

if (someVar.hasOwnProperty('someProperty') ) {
 // Do something();
} else {
 // Do somethingElse();
}

What is the right use/explanation of hasOwnProperty('someProperty')?

Why can't we simply use someVar.someProperty to check if an object someVar contains property with name someProperty?

What is a property in this case?

What property does this JavaScript check?

Answer

James Allardice picture James Allardice · Feb 22, 2012

hasOwnProperty returns a boolean value indicating whether the object on which you are calling it has a property with the name of the argument. For example:

var x = {
    y: 10
};
console.log(x.hasOwnProperty("y")); //true
console.log(x.hasOwnProperty("z")); //false

However, it does not look at the prototype chain of the object.

It's useful to use it when you enumerate the properties of an object with the for...in construct.

If you want to see the full details, the ES5 specification is, as always, a good place to look.