Search code examples
javascriptnode.jsarraysgoogle-chrome

Why `[1, 2, 3]` is not showing as an `Array(3)` in Console?


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)?



Solution

  • 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).