AceDevHub
Advanced JavaScript Interview QuestionsAdvancedCode Output

JavaScript · Question 75

How do sparse arrays and empty slots behave differently from array elements whose value is undefined?

Direct answer

An empty slot means the property for that index does not exist, while an element containing undefined is an existing property with the value undefined; many array methods observe that distinction.

sparse-vs-undefined.js
const a = [, 2];
const b = [undefined, 2];

console.log(0 in a, 0 in b);
console.log(a.map((x) => x * 2));
console.log(b.map((x) => x * 2));
Output
false true
[, 4]
[NaN, 4]

Compare const a = [ , 2 ]; const b = [undefined, 2];. Both arrays have length 2 and reading index 0 produces undefined, but 0 in a is false whereas 0 in b is true. The first array has a hole; the second has an actual element.

Many callback-based array methods such as map(), forEach(), and filter() skip missing indices rather than invoking the callback for a hole. Other mechanisms can materialize holes as undefined values, so changing iteration strategy can change observable behavior.

  • Array length is based on index range, not the number of existing properties.
  • Deleting an array element with delete arr[i] can create a hole without shrinking length.
  • When dense data is intended, prefer operations such as splice() or explicit filtering instead of leaving accidental holes.