Search code examples
javascriptnode.jsgoogle-chromeobjectprototype

In Javascript, why does Object.getPrototypeOf([1,2]) returns an empty list?


In Chrome 42.0, I assign a value to myArray using var myArray = [1,2],

I expect Object.getPrototypeOf(myArray) will be like this (screenshot from here)..

picture1

However, when I evaluate the code in REPL, I only got an empty list:

enter image description here

Does anyone have any ideas about this?


Solution

  • Because the console is trying to give you its most useful representation of what you've asked for. It sees that what you've passed it is an array (Array.isArray(Object.getPrototypeOf([1,2])) is true), so it shows it using its mechanism for showing arrays. Since the prototype array that all arrays inherit from is empty, you just see [].

    It does the same sort of thing for non-array objects:

    Object.getPrototypeOf({foo:"bar"})
    => Object {}
    

    (I'm using Chrome.)

    Consoles do a fair bit of interpretation on what you pass them. Some of that interpretation isn't always useful. Example:

    var a = [];
    => undefined
    a.foo = "bar";
    => "bar"
    a
    => []
    

    Whereas console.log(a) shows the more useful

    [foo:"bar"]
    

    E.g., an array with a non-element property, foo, with the value "bar".