JavaScript Sparse Arrays: Holes versus Undefined Values
Quick answer
A hole is an absent indexed property, not an explicitly stored undefined. Distinguishing these matters because array methods do not all traverse the same way.
How it works
For ordinary arrays without inherited numeric properties, map, filter, reduce, some, every and forEach skip holes. Find-family methods, for...of and spread read each position; holes produce undefined. Map preserves hole positions, while filter compacts accepted elements. Object.hasOwn(a, i) checks own presence. Prototype properties can affect index lookup and iteration checks.
const a = [, undefined, 5];console.log(Object.hasOwn(a,0), Object.hasOwn(a,1), a.length);Expected output in Node.js:
false true 3Only index 1 explicitly stores undefined.
const a = [, 2, , 4];let calls = 0;a.map(n => { calls++; return n; });console.log(calls, Object.hasOwn([...a],0));Expected output in Node.js:
2 trueMap skips holes, but spread materializes them.
Common mistakes
Do not infer presence from a[i] === undefined. JSON serialization cannot reliably distinguish holes from explicit undefined array entries.
Practice
Compare map callback counts with spread and Object.hasOwn on a sparse array.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Sparse Arrays: Holes versus Undefined Values — Knowledge Check
Apply the taught concept and predict the output.
For [ , 4 ] with no inherited numeric properties, what is the length after map(x => x * 2)?
Which operation reads ordinary holes as undefined rather than skipping them?
Which check directly distinguishes an own undefined element from a hole?
What is the exact console output in JavaScript Sparse Arrays: Holes versus Undefined Values example 1?
const a = [, undefined, 5];console.log(Object.hasOwn(a,0), Object.hasOwn(a,1), a.length);What is the exact console output in JavaScript Sparse Arrays: Holes versus Undefined Values example 2?
const a = [, 2, , 4];let calls = 0;a.map(n => { calls++; return n; });console.log(calls, Object.hasOwn([...a],0));