2

So I was playing abound in the V8 console and I did

Object.getOwnPropertyNames([])

I expected to get [] as a result, however ["length"]

SO this means that instead of being part of the prototype chain, length is a member property of all Array objects.

Is this a bug, or is there any design or specific reason length is not the part of a prototype chain?

Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
  • 1
    Also significant, `length` is not a function that calculates the length, but a property that stores the length. If it were the former it could have been defined on the prototype. – Derek Kraan Dec 29 '17 at 10:20
  • Possible duplicate of [Array.length vs Array.prototype.length](https://stackoverflow.com/questions/28240173/array-length-vs-array-prototype-length) – LW001 Dec 29 '17 at 10:20
  • Also see https://stackoverflow.com/questions/22658488/object-getownpropertynames-vs-object-keys – dfsq Dec 29 '17 at 10:22

3 Answers3

3

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.

Rajesh
  • 24,354
  • 5
  • 48
  • 79
2

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.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
0

Because it is not enumarable (Object#propertyIsEnumerable).

Further reading: Enumerability and ownership of properties

console.log([].propertyIsEnumerable('length'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392