skip to Main Content

When I inspect an instance of an array (like const arr = [1, 2, 3];), the prototype chain for that array will point to Array.prototype.

However, I am not able to understand why Array.prototype is displayed as an empty array (Array(0)) in Chrome console.log()?

enter image description here

I have gone through post1 and post2 but still not able to understand this basic concept.

Why [1, 2, 3] in the console in not showing as an Array(3)?

2

Answers


  1. Array(0) here refers to the [[Prototype]] value, i.e. to Array.prototype.

    For instance if you log

    const obj = {
      arr: [1, 2, 3]
    }
    

    You can see that the actual Array in the arr property is logged as Array(3), but that the [[Prototype]] of this Array is marked as an empty Array.
    screenshot of the console showing that an Object's prototype is "Object", while an Array's one is Array(0), but that the actual Array is Array(3)

    That’s because, like I pointed to you in your now deleted question, Array.prototype is actually an Array itself. See this Q/A for more details.

    So if you do something like

    Array.prototype[2] = "bar";
    const arr = [1, 2, 3];
    

    The Array’s Prototype will now say Array(3).

    Login or Signup to reply.
  2. When you inspect [1, 2, 3] in the console, you are inspecting the instance of the array, which is Array(3) because it has 3 elements.
    Array.prototype, however is an empty array itself (Array(0)), and that’s what is displayed when you inspect the prototype of any array instance.
    Array.prototype contains all the methods not the instance of the element.
    Hope you get it, of not then do let me know.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search