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!
Top comments (1)
Extra materials: