Why Is Length A Property Of `array` Not `array.prototype` Chain
Solution 1:
That is not a bug. By definition, Object.getOwnPropertyNames
will return all the enumerable and non-enumerable own properties of an object. When it comes to an array, length is an own property but its enumerable property is false. That's the reason why it is getting included in the result.
you can test it with the following snippet,
console.log(Object.getOwnPropertyDescriptors([]));
The above code will return the descriptors of all the own properties. Inspect it, you will get to know about its enumerable property.
Solution 2:
Prototype properties are shared across objects. So if length is put on prototype, all the array objects will have same length, which is wrong. Length signifies number of elements in current array and should remain property of self.
Solution 3:
Because it is not enumarable (Object#propertyIsEnumerable
).
Further reading: Enumerability and ownership of properties
console.log([].propertyIsEnumerable('length'));
Post a Comment for "Why Is Length A Property Of `array` Not `array.prototype` Chain"