Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only custom object properties are shown during for-in loop

Tags:

javascript

Array.prototype.myFeature = function() {};

var arr = ['some', 'items'];

for (var prop in arr) {
  console.log(prop);
}

The output for that code will be: 0, 1, myFeature.

The question is: why only custom added function to the Array prototype is outputed, instead of all the function that exists in prototype?

like image 272
Src Avatar asked Apr 16 '18 16:04

Src


2 Answers

This is because built-in array methods are defined to be non-enumerable, while properties created by ordinary assignment are enumerable. Internally, properties have behavioral features specified by their associated property descriptor which is defined at property-creation time. One feature supplied in this way is the property's enumerability.

Compare

> Object.getOwnPropertyDescriptor(Array.prototype, "join")
{value: ƒ, writable: true, enumerable: false, configurable: true}

and

> Object.getOwnPropertyDescriptor(Array.prototype, "myFeature")
{value: ƒ, writable: true, enumerable: true, configurable: true}

The first property descriptor object has enumerable: false while the second has enumerable: true. Non-enumerable properties are not enumerated in for-in loops.

You can define your own non-enumerable property with Object.defineProperty:

Object.defineProperty(Array.prototype, "myFeature", { value: function() {}, enumerable: false });
like image 52
apsillers Avatar answered Oct 18 '22 20:10

apsillers


Per the docs:

The for...in statement iterates over the enumerable properties of an object. For each distinct property, statements can be executed.

Seems, only these three properties are enumerable. So for...in only iterates over them.

like image 23
31piy Avatar answered Oct 18 '22 20:10

31piy