When do I need to use hasOwnProperty()?

Object.hasOwnProperty determines if the whole property is defined in the object itself or in the prototype chain.

In other words: do the so-called check if you want properties (either with data or functions) coming from no other place than the object itself.

For example:

function A() {
   this.x = "I'm an own property";
}

A.prototype.y = "I'm not an own property";

var instance = new A();
var xIsOwnProperty = instance.hasOwnProperty("x"); // true
var yIsOwnProperty = instance.hasOwnProperty("y"); // false

Do you want to avoid the whole check if you want own properties only?

Since ECMAScript 5.x, Object has a new function Object.keys which returns an array of strings where its items are the own properties from a given object:

var instance = new A();
// This won't contain "y" since it's in the prototype, so
// it's not an "own object property"
var ownPropertyNames = Object.keys(instance);

Also, since ECMAScript 5.x, Array.prototype has Array.prototype.forEach which let’s perform a for-each loop fluently:

Object.keys(instance).forEach(function(ownPropertyName) {
    // This function will be called for each found "own property", and
    // you don't need to do the instance.hasOwnProperty check any more
});

Leave a Comment