"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 === 30 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
1does not exist (1 in sparse->false) sparse.length === 3, but there are actually only 2 elements
How "holes" appear
- When using
delete:
javascript
const arr = [1, 2, 3];
delete arr[1];
console.log(arr); // [1, <1 empty item>, 3]- When specifying a gap in a literal:
javascript
const arr = [1, , 3];- When increasing
lengthmanually:
javascript
const arr = [1, 2];
arr.length = 5;
console.log(arr); // [1, 2, <3 empty items>]Behavior during iteration
| Method | Dense array | Sparse array |
|---|---|---|
for | goes through all indexes | goes through all indexes |
for...of | goes through all values | skips empty ones |
forEach() | goes through every element | skips "empty" ones |
map(), filter(), reduce() | skip "empty" ones | |
in | checks for the index | returns false for holes |
Object.keys() | shows only existing indexes | skips 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
nullorundefinedas explicit "empty" values.
In short:
| Array type | Description | Example | Behavior |
|---|---|---|---|
| Dense | All indexes are occupied | [1, 2, 3] | Predictable, fast |
| Sparse | Has missing indexes | [1, , 3] | Methods skip empty ones, slower |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.