1

Since Array.prototype itself returns an empty array, where do all functions come from?

Why I can call functions something like Array.prototype.sort, even Array.prototype is not object?

Array.prototype.__proto__ is an object.

I have same question on the case of Function.prototype.

1
  • 2
    Why do you think Array.prototype is not an object? Arrays (and functions) are both objects in JS. Commented Feb 7, 2017 at 3:45

2 Answers 2

2

Array.prototype is an object, and most functions you used for array come from it. So it's the prototype.

Open chrome dev bar, and check it like the below image.

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for console.debug (unfortunately not standard). Complementing: Array.prototype.sort does not show in console.log because it's not enumerable property. Check with Array.prototype.propertyIsEnumerable("sort"). console.log implementation uses Object.keys, and, as pointed in the docs, The Object.keys() method returns an array of a given object's own enumerable properties
Thank you for your comment, xdazz. Yes, I checked on chrome console and I got a question. It says Array[0] or [] when you call Array.prototype. Array.isArray(Array.prototype) returns true. Array is one of the built-in objects so that it is object.
0

even Array.prototype is not object?

How did you get that idea? It is an object:

typeof Array.prototype // "object"

As such it can have properties like every other object. And it does:

Array.prototype.hasOwnProperty("sort") // true
Array.prototype.sort // function(compare) { … }

This is the same for every other array, you can create custom properties on them like on every javascript object:

var foo = [];
foo.bar = "baz";
typeof foo.bar // "string"
Array.isArray(foo) // true

6 Comments

Thank you for your comment. Yes typeof Array.prototype returns "object" but Array.isArray(Array.prototype) returns also true which means it is array natives, isn't it? How can the functions be retrived from array.?
Every array is just an object with a special-behaving length property (and possibly some engine optimisations), but a standard js object in every other regard.
I see. Why Array.prototype is not contained plain key/value object instead of array or function. Using array as key/value hash table sounds not good practice..
That's a different question with a simple but unsatisfying answer :-)
Ahh, thank you for sharing it. I am confused because I did not expect javascript uses array for hashtable-like purpose.. Thank you for all your comments.
|