Glossary / Sparse arrays

Sparse arrays

A sparse array has missing index properties within its length range. A hole is different from an element whose value is explicitly undefined: both read as undefined, but property checks and many array methods distinguish them. Sparse arrays can arise from deleting an index, assigning a far-ahead index, or constructing arrays with empty slots.

Holes versus undefined

const hole = [,];
const explicit = [undefined];

hole.length; // 1
0 in hole; // false
0 in explicit; // true

delete array[index] removes the property but leaves the array length and later indices unchanged. splice removes and shifts elements, producing a dense result. Methods such as map, forEach, and filter generally skip absent indices, while array iterators and spread produce undefined values for holes. Object.keys lists only present enumerable indices. These differences can create subtle bugs in transformations and serialization.

Sparse arrays may behave differently in engine optimization and are rarely desirable for application lists. Use splice for removal, explicit sentinel values when missing positions are meaningful, or typed arrays for dense numeric buffers. Test property presence when hole state matters rather than relying on reads.

Interview questions

  1. How distinguish a hole from explicit undefined? Check index in array or Object.hasOwn(array, index).
  2. Does delete shrink the array? No; it leaves a hole and preserves length.
  3. How remove and shift elements? Use splice.
  4. Do all array methods treat holes identically? No; some skip holes, while iterators may yield undefined.

References