DEV Community

Cover image for Why an array is an object in JavaScript?
Nick
Nick

Posted on

Why an array is an object in JavaScript?

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__()
}


Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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()
  ...
]


Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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.

indices handling

πŸ‘‰ 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.

length property


P.S. Follow me on Twitter for more content like this!

Top comments (1)

Collapse
 
fromaline profile image
Nick