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?

3
  • 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. Commented Dec 29, 2017 at 10:20
  • Possible duplicate of Array.length vs Array.prototype.length Commented Dec 29, 2017 at 10:20
  • Also see stackoverflow.com/questions/22658488/… Commented Dec 29, 2017 at 10:22

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So prototype chains, in essence are singleton?
@Ayush Gupta yes
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.

Comments

0

Because it is not enumarable (Object#propertyIsEnumerable).

Further reading: Enumerability and ownership of properties

console.log([].propertyIsEnumerable('length'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.