JS Array

heisdev profile image dev ・1 min read

Recently read an article on medium about JS Arrays which said as follows:

In Js, an array internally is also an object only

for a regular array like this
['a','b','c'] its equivalent object is { 0: 'a', 1: 'b', 2:'c', length: 3}
This is by definition a dense array

In JS, there is also the concept of sparse array
['a', , 'c'] its equivalent object is { 0: 'a', 2:'c', length: 3}

The empty hole we refer to is called an Elision

So in order to replicate holes/Elision , you just need not set the index values in the object but set the length property,

[,] equivalent is {length: 1}

but if you try
a = [,]; b = [undefined];
a[0] === b[0], it will return true though a[0] is an elision
because technically, elision is treated as an undefined value

but when u represent a = [,], the browser sees the length property of the object a and finds 1

But if it accesses the index 0, it hasn't been set also doesn't have a value and hence its undefined, but its represented as a hole/elision (as [empty] in chrome v8)

So basically in Js a hole/elision is created when there is a mismatch between index assignment and length property of an object (of type array)

Posted on by:


markdown guide

Interesting. Wonder why it's a thing though lol