Posted on: October 26, 2022|3 min read|Amrish Kushwaha

What are sparse arrays in javascript?

What are sparse arrays in javascript?

What are sparse arrays?

A sparse array is an array which contains empty slots.

An empty slot is something that contains no value, not even undefined.

Typically, the length property of an array is equal to the number of elements in that particular array but if the array is sparse, then the value of the length property is greater than the number of elements in that array.

Dense array:

The dense array is an array which doesn’t contain empty slots meaning that every place (index) contains an element. In dense arrays, the value of the length property is equal to the number of elements of the array

How does a sparse array get created?

There are few ways to create sparse array:

  • Array Constructor

    const arr1 = Array(4)

    One of the ways to create a sparse array is by using Array Constructor. In the above example, an array of length 4 will be created having every place contains empty slot.

  • Consecutive commas

    const arr3 = [1, 2, , 4]

    Here are two consecutive commas which will make arr3 a sparse array. This is one of most obvious way to create a sparse array.

  • Elongating array length

    If we increase the length of array by setting the larger integer, then the extra space which is created by elongating that array will be empty and the array will become a sparse array.

    const d = [1, 2] d.length = 4 // [ 1, 2, <2 empty items> ]
  • Directly setting a slot with an index greater than the array.length

    This is also another way to convert dense array to sparse array 🙂

    const c = [1, 2] c[3] = 4 // [ 1, 2, <1 empty item>, 4 ]
  • Deleting an element

    If we delete an element from the array, that place will be empty.

    const e = [1, 2, 3, 4] delete e[2] // [ 1, 2, <1 empty item>, 4 ]

Sparse array's behaviour with JS operations?

In some operations, sparse arrays' empty slots are treated as though they are filled with undefined

Some of the examples are here:

// Create a sparse array const arr = [1, 2, , 4]
  1. Indexed access:

    When we try to access the empty slot using the index, it returns undefined as result.

    console.log(arr[2]) // undefined
  2. Spreading

    When we spread out the sparse array, empty slots are filled with undefined

    const anotherArr = [...arr] // [1,2,undefined, 4]
  3. In for...of usage:

    In for…of, the empty slots are treated as undefined

    for (const element of arr) { console.log(element) } // 1 2 undefined 4
  4. Join method

    join() treats empty slots the same as undefined and produces an extra separator

    const array1 = ["1", , "3"] const result = array1.join(".") console.log(result) // 1..3

Similarly, there are other operations which treat empty slots to undefined. Check here for a complete list.


In some other operations, empty slots are skipped entirely

const arr = [1, 2, , 4]
  1. forEach method

    The forEach method skips the empty slots of the sparse array.

    arr.forEach(i => console.log(i)) // Logs "1 2 4"
  2. Property enumeration

    In property enumeration also empty slots are skipped

    const keys = Object.keys(arr) // ['0', '1', '3']
  3. Spreading into an object uses property enumeration

    const objectSpread = { ...arr } // { '0': 1, '1': 2, '3': 4 }

Similarly, there are other operations where empty slots are skipped. Check here for a complete list.

Generally, the older methods will skip empty slots, while newer ones treat them as undefined

Working with sparse array:

It is always better to work with dense array rather than sparse array to avoid any bad consequences. So check whether the array is dense or not before proceeding further.

const any_arr = [...] // some array function isDenseArray(arr) { return arr.length === Object.keys(arr).length } if(Array.isArray(any_arr)) { if(isDenseArray(any_arr)) { console.log("Dense Array!") } else { console.log("Sparse Array, proceed with your own risk!") } }

I hope that you have liked this article. Keep coding and keep solving problems.

About author:

Amrish Kushwaha

Amrish Kushwaha

I am Amrish Kushwaha. Software Engineer, Maker, Writer. I am currently focused on frontend development with curiosity of building end to end software system. Currently I am working at Rafay Systems. I love to write as well as build side projects when I am free.

Frontendroom
© 2023 · Copyright Frontendroom