Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "for-in" loop doesn't iterate through the prototype properties?

Tags:

javascript

Let's create a new object:

var dict = {};

Known fact is that after creating a new object, this new object inherits the Object.prototype . So when I try to check if the prototype's properties were inherited I do "toString" in obj for which I get true. But when I want to put all the properties of the newly created object into an array I would see that the array is empty after finishing filling up. Have a look on the code below:

var names = [];

for (var name in dict) {
  names.push(name);
}; 
names.length;

Fail to see why it happens.

like image 473
Anton Kasianchuk Avatar asked Sep 29 '22 08:09

Anton Kasianchuk


1 Answers

As many said in the comments, the For-In loop enumerates only the enumerable properties in the prototype chain, and the inherited toString property is not enumerable.

If you want to iterate through the non-enumerable properties of the object prototype to see if "ToString" is there then you should get the object prototype and get its enumerable and non-enumerable properties using the getOwnPropertyNames method:

var dict = {};
var objPrototype = Object.getPrototypeOf(dict);

var propertyNames = Object.getOwnPropertyNames(objPrototype);

propertyNames.length;
like image 120
Faris Zacina Avatar answered Oct 03 '22 00:10

Faris Zacina