Advertisement
Advanced JavaScript, Arrays & Array Methods

Why can array holes (sparse arrays) behave unexpectedly with iteration methods?

Short answer

Methods like forEach, map, and filter skip empty slots in sparse arrays entirely rather than treating them as undefined, which can silently produce shorter results than expected. for...of and the spread operator, however, treat holes as undefined.

Save JavaScript mock interview
Advertisement
AModel answer
Methods like forEach, map, and filter skip empty slots in sparse arrays entirely rather than treating them as undefined, which can silently produce shorter results than expected. for...of and the spread operator, however, treat holes as undefined.
const arr = [1, , 3];
arr.forEach(x => console.log(x)); // logs 1, 3 (skips the hole)
console.log([...arr]); // [1, undefined, 3]
Real-world example
A bug caused by delete arr[i] leaving a hole that silently vanishes from forEach-based processing.
Likely follow-ups
  • How do you create a hole-free array of a given length?
Related topics