0

I'm trying to understand the prototypical chain in JavaScript. What I think to know so far (please correct me where I'm wrong):

(Almost) everything in JavaScript is an object. Arrays are also objects, therefore they inherit certain properties, like methods, from the parent. So every array or object I create is actually a child of the object class.

BUT: If I create a new array and try to tap into the properties by doing

console.log(myArray.prototype)

I get undefined. And if I try

console.log('3', Array.prototype);

I get an empty array. Now I have a few questions:

  1. Can someone explain to me why I can't seem to tap into it?
  2. It seems like every array-method-documentation specifies Array.prototype.map() and I don't understand why we have to point it out like that
  3. Why exactly did the class based approach get rid of the prototype keyword (even though the functionality behind it seems to be the same still)

Thank you guys!

Sam
  • 41
  • 3
  • _"the object class"_ - not the object class, but the "Object" object itself. – evolutionxbox Aug 08 '22 at 12:23
  • 2
    Also, if you want to know what object the prototype of something is, use `Object.getPrototypeOf` – evolutionxbox Aug 08 '22 at 12:25
  • @Axekan `__proto__` is a [deprecated property](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) and shouldn't be relied upon. – evolutionxbox Aug 08 '22 at 12:27
  • 1
    The `prototype` property isn't the prototype of the object. The `prototype` property exists on most functions (for instance, function `X` has `X.prototype`) and refers to the object that will be assigned to an object created by using `new` with that function (`new X`). The prototype of `myArray` is accessible by using [`Object.getPrototypeOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf). (Which is used by the `__proto__` accessor property defined by `Object`, but don't use that, it's only there for compatibility with old code.) – T.J. Crowder Aug 08 '22 at 12:28
  • 2
    *"...So every array or object I create is actually a child of the object class...."* Oddly, no. :-) Every object (including every array) is an object (bit circular there, sorry), but not all of them are instances of `Object` in the sense of being `instanceof Object`. That's because to be `instanceof Object`, it would have to have `Object.prototype` in its prototype chain, and **most** objects do, but not all. It's possible to create an object with no prototype at all (`Object.create(null)`), which is not `instanceof Object` (nor would anything using that as its prototype). It's an edge case. – T.J. Crowder Aug 08 '22 at 12:32

0 Answers0