1

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..."

  • 2
    "*As we know, array's length property resides on `Array.prototype`*" - uh, not really, it doesn't. – Bergi Aug 05 '21 at 22:35
  • If the property were on the prototype object, then how could it possibly be different for an array instance with 2 elements and an array with 200? – Pointy Aug 05 '21 at 22:39
  • @Pointy I assume you could implement that with a getter on the prototype that reads the length from `this`? But that doesn't seem like it would be as efficient as just having each array store its own length, and may not have worked in early ES versions either. – Robin Zigmond Aug 05 '21 at 22:40
  • 1
    @RobinZigmond yes that would be possible but the `.length` property long preceeds the getter facility; `.length` has been there since the 90s. It's an instance property. – Pointy Aug 05 '21 at 22:44

1 Answers1

2

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • "Array.prototype is itself an array" that was the missing point – another knowledge gap closed, thanks – zepeersGily Aug 06 '21 at 12:15
  • @zepeersGily Yeah, it's a really weird design decision, and hardly known because it's not really important for anything. It probably wouldn't be an array if JS was designed today, but it is the way it is and can't be changed for compatibility reasons. – Bergi Aug 06 '21 at 16:34
  • See also [all](https://stackoverflow.com/a/27306692/1048572) [these](https://stackoverflow.com/a/55270097/1048572) [answers](https://stackoverflow.com/a/34106934/1048572) touching upon the subject. – Bergi Aug 06 '21 at 16:35