Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Why does the "for in" loop pick variables from __proto__?

I added a method trigger to the prototype of Object:

Object.prototype.trigger = function() {
    //  ...
    return this;
};

And then have a "for in" loop:

var obj = { 4: 15, 10 : 41, 11 : 46, 12 : 51, 20 : 74 }
for( item in obj ) {
    foo( obj[item] );
}

But this loop has 6 iterations instead of 5. The last iteration is with key:

item = "trigger"

Why is the loop iterating over the __proto__ part of the object?

like image 773
Alex Shul Avatar asked May 16 '19 12:05

Alex Shul


1 Answers

for...in goes over all of the object properties without distinguishing between properties on the object itself or any of its ancestors.

In order to go over only properties defined on the object itself, you can use Object.prototype.hasOwnProperty:

const obj = { 4: 15, 10 : 41, 11 : 46, 12 : 51, 20 : 74 }
for( item in obj ) {
  if(obj.hasOwnProperty(item) {
    foo( obj[item] );
  }
}

// will ignore the trigger func and everything else defined on any prototype
like image 146
Thatkookooguy Avatar answered Sep 26 '22 09:09

Thatkookooguy