Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 564
Robert Rocha Avatar asked Jul 14 '26 21:07

Robert Rocha


2 Answers

Because Object.prototype.hasOwnProperty is non-enumerable:

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

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

like image 145
Oriol Avatar answered Jul 17 '26 17:07

Oriol


Because hasOwnProperty is not enumerable , you can test it using

console.log(Object.getOwnPropertyDescriptor(Object.prototype, "hasOwnProperty").enumerable)
like image 20
KarimS Avatar answered Jul 17 '26 15:07

KarimS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!