What Is a Sparse Array in JavaScript?

A sparse array in JavaScript refers to an array that has one or more empty slots (or "holes") in it. This can happen:

  1. When an array is created with a length that is larger than the number of elements that it initially contains, or;
  2. When elements are deleted from an array.

This happens because arrays are indexed collection, where each element appears in a set sequence. Deleting an item from such a collection, does not automatically re-index the array, thus leaving holes/gaps in it instead. Similarly, when you extend an array by modifying it's length without adding a new element, it too creates empty slots (as the indexes don't point to any element yet).

You can see this demonstrated in the following examples, where a sparse is created by setting a larger length than the number of elements the array has:

// array constructor:
console.log(Array(5)); // [empty x 5]
// consecutive commas in array literal:
console.log([1, 2, , , 5]); // [1, 2, empty x 2, 5]
// directly setting `array.length` greater than total array elements:
const arr = [1, 2];
arr.length = 5;
console.log(arr); // [1, 2, empty x 3]
// directly setting a slot with index greater than `array.length`:
const arr = [];
arr[4] = 5;
console.log(arr); // [empty x 4, 5]

Similarly, when you delete an element from an array, it leaves holes (or creates empty slots) in the array, making it sparse:

// deleting an element:
const arr = [1, 2, 3, 4, 5];
delete arr[2];

console.log(arr); // [1, 2, empty, 4, 5]

Please note that empty slots are different from slots filled with the value undefined. However, some methods treat them as undefined, while others preserve the empty slots.

Sparse arrays can matter because they can lead to unexpected behavior when iterating or manipulating the array; due to the "holes" in the array:

  1. The length property of the array does not accurately reflect the number of elements in the array;
  2. Array methods behave inconsistently — i.e. some array methods ignore/skip empty slots while others treat them as undefined.

Therefore, you should avoid using sparse arrays whenever possible as they can lead to unexpected behavior when iterating or manipulating the array. Instead, it's better to use any of the following:

  • Dense arrays (opposite of sparse arrays) — they are arrays that do not have empty slots (or "holes") in them;
  • Typed arrays (such as Int8Array, Uint8Array, Int16Array, etc.) — they can't have holes as they are of fixed size and are initialized with zeros;
  • Non-indexed collections (such as Map, Set, using object as a map, etc.) — they don't have holes as they use unique keys to access elements in a collection.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.