Skip to main content

"dense" and "sparse" array

Definitions

Dense array

An array in which all indexes are occupied by elements: from 0 to length - 1.

That is:

  • there are no "missing" indexes (holes),
  • every index actually exists on the object.
javascript
const dense = [10, 20, 30];

Here:

  • indexes: 0, 1, 2
  • dense.length === 3
  • 0 in dense -> true, 1 in dense -> true, 2 in dense -> true

Sparse array

An array in which some indexes are missing: it has "holes".

javascript
const sparse = [10, , 30]; console.log(sparse); // [10, <1 empty item>, 30]

Here:

  • index 1 does not exist (1 in sparse -> false)
  • sparse.length === 3, but there are actually only 2 elements

How "holes" appear

  1. When using delete:
javascript
const arr = [1, 2, 3]; delete arr[1]; console.log(arr); // [1, <1 empty item>, 3]
  1. When specifying a gap in a literal:
javascript
const arr = [1, , 3];
  1. When increasing length manually:
javascript
const arr = [1, 2]; arr.length = 5; console.log(arr); // [1, 2, <3 empty items>]

Behavior during iteration

MethodDense arraySparse array
forgoes through all indexesgoes through all indexes
for...ofgoes through all valuesskips empty ones
forEach()goes through every elementskips "empty" ones
map(), filter(), reduce()skip "empty" ones
inchecks for the indexreturns false for holes
Object.keys()shows only existing indexesskips empty ones

Comparison example:

javascript
const dense = [1, 2, 3]; const sparse = [1, , 3]; dense.forEach(v => console.log(v)); // 1, 2, 3 sparse.forEach(v => console.log(v)); // 1, 3 (index 1 skipped) console.log(Object.keys(dense)); // ["0", "1", "2"] console.log(Object.keys(sparse)); // ["0", "2"]

Impact on performance

Sparse arrays:

  • run slower,
  • are optimized worse by the V8 engine,
  • and often behave "strangely" during iteration.

That is why in real projects it is better to avoid "holey" arrays and use null or undefined as explicit "empty" values.


In short:

Array typeDescriptionExampleBehavior
DenseAll indexes are occupied[1, 2, 3]Predictable, fast
SparseHas missing indexes[1, , 3]Methods skip empty ones, slower

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.