I recently knew that Array.prototype
is itself an array ([]
).
You are right, it is an array. The specification says in §15.4.4, Properties of the Array Prototype Object:
The Array prototype object is itself an array; its [[Class]]
is "Array"
, and it has a length
property (whose initial value is +0
) and the special [[DefineOwnProperty]]
internal method described in 15.4.5.1.
But an amazing thing is that it is not the instance of Array object. How is that possible? What is the reason for this?
If you tried Array.prototype instanceof Array
then the result will indeed be false
. Why? Because of the way the instanceof
operator works. It compares the prototype of an object with the value of the prototype
property of the constructor function.
I.e. in this case it does
Object.getPrototypeOf(Array.prototype) === Array.prototype
As we can already see in this comparison, we are trying to test whether Array.prototype
is its own prototype, which is impossible. The specification also mentions in the same paragraph:
The value of the [[Prototype]]
internal property of the Array prototype object is the standard built-in Object prototype object (15.2.4).
That is, Object.getPrototypeOf(Array.prototype) === Object.prototype
and Object.prototype !== Array.prototype
. Hence instanceof
yields false
, but Array.prototype
is an array nonetheless.
Array.prototype
has many properties but when u log i.e console.log(Array.prototype.length)
, the output is '0'.
0
being the value of Array.prototype.length
is defined in specification (see above).
It would be great if u let me know the difference in element and property of an array
An element of an array is a property with a property name that is a positive 32-bit integer (or 0
). A property is any other property which does not have such a property name. Those are not considered by any array operations.
The specification provides a more precise description in §15.4, Array Objects:
Array objects give special treatment to a certain class of property names. A property name P
(in the form of a String value) is an array index if and only if ToString(ToUint32(P))
is equal to P
and ToUint32(P)
is not equal to 232−1. A property whose property name is an array index is also called an element.
So you see, if a property name is converted to (the string representation of) an unsigned 32-bit integer and still has the same value, then it is an array index and the associated value is an element of the array.
The specification continuous with
The value of the length
property is numerically greater than the name of every property whose name is an array index;
We just learned which property names are considered to be array indexes, those that can be converted to unsigned integers. By that definition, "a"
is not an array index, so
var x = [];
x['a'] = 42;
does not change the length
property. But "3"
is an array index, so
x["3"] = 42;
changes the length
property to 4
.