javascriptinheritanceprototypeprototypal-inheritanceprototype-chain

JavaScript iterating over object properties and the prototype chain


MDN states:

Also, when iterating over the properties of an object, every enumerable property that is on the prototype chain will be enumerated.

So I tried this:

var x = {a: "I am a"};
var z = Object.create(x);

for( i in z )
{
    console.dir( i );

    if( i == "hasOwnProperty" ) {
        console.log( 'found hasOwnProperty' );
    }
}

Outputs only a but not hasOwnProperty. Why?


Solution

  • Because Object.prototype.hasOwnProperty is non-enumerable:

    Object.getOwnPropertyDescriptor(Object.prototype, 'hasOwnProperty')
      .enumerable // false
    

    Therefore, it's not iterated by the for...in loop.