Why an array is an object in JavaScript?
Nick
Posted on February 8, 2022
JS is a prototype-based language, so there are only primitive types and objects. It grants flexibility but makes things more confusing at the same time.
👉 Everything is an object!
Implementation of all non-primitive values in JavaScript is object-based.
Simply put, JavaScript has a single prototypical object from which all other objects get their initial properties. We can get it by accessing __proto__
.
Object.getPrototypeOf(Object).__proto__;
Object.getPrototypeOf(Array).__proto__;
Object.getPrototypeOf(Boolean).__proto__;
// The prototypical object of every object
{
constructor: Æ’ Object()
hasOwnProperty: Æ’ hasOwnProperty()
isPrototypeOf: Æ’ isPrototypeOf()
propertyIsEnumerable: Æ’ propertyIsEnumerable()
toLocaleString: Æ’ toLocaleString()
toString: Æ’ toString()
valueOf: Æ’ valueOf()
__defineGetter__: Æ’ __defineGetter__()
__defineSetter__: Æ’ __defineSetter__()
__lookupGetter__: Æ’ __lookupGetter__()
__lookupSetter__: Æ’ __lookupSetter__()
__proto__: (...)
get __proto__: Æ’ __proto__()
set __proto__: Æ’ __proto__()
}
👉 Every array is an object too!
The array type is not an exception here. Array
global class is a global object and an array literal is just an instance of the Array
global class.
In turn, a direct prototype of the array type contains all its special methods, like fill, find, etc.
// true
Object.getPrototypeOf(Array).__proto__ === Object.getPrototypeOf(Object).__proto__
Object.getPrototypeOf([]).__proto__ === Object.getPrototypeOf(Object).__proto__
Object.getPrototypeOf([])
[
at: Æ’ at()
concat: Æ’ concat()
constructor: Æ’ Array()
copyWithin: Æ’ copyWithin()
entries: Æ’ entries()
every: Æ’ every()
fill: Æ’ fill()
filter: Æ’ filter()
find: Æ’ find()
findIndex: Æ’ findIndex()
findLast: Æ’ findLast()
findLastIndex: Æ’ findLastIndex()
flat: Æ’ flat()
...
]
👉 How is it implemented in the JavaScript engine?
Similarly, arrays are a special case of objects inside the JavaScript engine.
But they have:
- special handling of indices
- a magical length property
To understand how objects work, check out my article.
👉 Indices handling
Array indices are represented as strings, that contain numbers.
So every element inside an array is associated with a numeric string.
👉 Length property
The length is just non-configurable and non-enumerable property. The JavaScript engine automatically updates its value once an element is added to the array or deleted from it.
P.S. Follow me on Twitter for more content like this!
Posted on February 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.