yaodebian @ yaodebian.me

Sparse Arrays And Iteration In Javascript

Sep 28, 2025

In JavaScript, an array hole (also called a sparse element) means that an index exists in the array but has no value assigned. For example:

// eslint-disable-next-line no-sparse-arrays
const arr = [1, , 3] // index 1 is a hole

Different iteration methods treat holes differently:

for...of

Example:

// eslint-disable-next-line no-sparse-arrays
for (const x of [1, , 3]) {
  console.log(x) // 1, undefined, 3
}

Array methods like forEach, map, reduce

// eslint-disable-next-line no-sparse-arrays
[1, , 3].forEach(x => console.log(x)) // 1, 3
// eslint-disable-next-line no-sparse-arrays
console.log([1, , 3].map(x => x)); // [1, <1 empty item>, 3
// eslint-disable-next-line no-sparse-arrays
[1, , 3].reduce((acc, cur) => acc.concat(cur), []) // [1, 3]

for...in

// eslint-disable-next-line no-sparse-arrays
for (const x in [1, , 3]) {
  console.log(x) // 0, 2
}

Summary

Base on the examples above, we can summarize the following points:

  1. for...of iterates over the values of the array, including holes.
  2. Array methods like forEach, reduce iterate over the values of the array, excluding holes. And map iterates over the values of the array, including holes.
  3. for...in iterates over the indices of the array, excluding holes.
> comment on mastodon / twitter
>
CC BY-NC-SA 4.0 2021-PRESENT © Anthony Fu