- When an array is created with a length that is larger than the number of elements that it initially contains, or;
- 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 = 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; 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:
lengthproperty of the array does not accurately reflect the number of elements in the array;
- Array methods behave inconsistently — i.e. some array methods ignore/skip empty slots while others treat them as
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
Int16Array, etc.) — they can't have holes as they are of fixed size and are initialized with zeros;
- Non-indexed collections (such as
Set, using object as a map, etc.) — they don't have holes as they use unique keys to access elements in a collection.
Hope you found this post useful. It was published . Please show your love and support by sharing this post.