javascriptinheritanceprototype-chain

Why is length property owned by an array object?


There are other examples, but for the sake of simplicity let's take the length property, what's that doing here:

[].hasOwnProperty("length")
//==> true

As we know, array's length property resides on Array.prototype so it's readily accessible from any array instance just by walking up the prototype chain, why copy it down? Has it something to do with the specific implementation in the browser? (code example above executed in chrome console). Even MDN clearly says that: "...methods and properties are not copied from one object to another in the prototype chain. They are accessed by walking up the chain..."


Solution

  • Simply: because every array instance has a different .length value.

    The .length property could have been a getter/setter that would be inherited from a shared prototype object, but the initial design of JavaScript went with a data property that is updated automatically with element creation/removal.

    length property resides on Array.prototype

    There exists an Array.prototype.length property, but only because Array.prototype is itself an array. Notice that its value is 0 - you wouldn't want that to be inherited to all arrays.