2
votes

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?

3

3 Answers

7
votes

Because Object.prototype.hasOwnProperty is non-enumerable:

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

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

1
votes

Because hasOwnProperty is not enumerable , you can test it using

console.log(Object.getOwnPropertyDescriptor(Object.prototype, "hasOwnProperty").enumerable)
0
votes

As answered above, each property of an object has an 'enumerable' flag. When the flag set to false the property will not be enumerated when iterating over object properties.

Object.prototype.hasOwnProperty is non-enumerable which mean is 'enumerable' flag set to false.

You can read an article I wrote on the topic here to deepen your knowledge.