Emmanuel Akinfulubi

JavaScriptArray

Sparse arrays and holes in JavaScript

Advanced · 4 min read

Most arrays have a value in every slot. A sparse array has gaps: slots that don't exist at all, even though they are counted in the length. These gaps are called holes, and different array methods treat them in different ways. Some skip them, some fill them with undefined, and some drop them.

You will rarely make a hole on purpose. They usually appear by accident, from new Array(5), delete xs[i] or a stray comma. In this tutorial you will make holes, learn how to spot one, and find out what the common methods do with them. Then you will see how to avoid them. You should know arrays, arrow functions and map, filter and forEach.

An array is an object with numbered keys

Under the hood, an array is an object whose keys are '0', '1', '2' and so on, plus a length. A hole is a key that is simply missing. That is different from a slot that exists and holds undefined.

The in operator asks "does this key exist?", which makes it the test for a hole:

JavaScript

const sparse = [1, , 3];            // the middle slot does not exist
const explicit = [1, undefined, 3]; // three real values

console.log(sparse.length, explicit.length); // 3 3
console.log(1 in sparse);   // false
console.log(1 in explicit); // true
console.log(sparse[1], explicit[1]); // undefined undefined

Reading either slot gives undefined, so you can't tell them apart by reading. Only in shows the difference.

Why it matters

The array methods were added to JavaScript at different times. The older ones (forEach, map, filter, reduce, some, every, indexOf) were defined to skip missing slots. The newer ones (Array.from, spread, for...of, includes, find) treat a hole as undefined. There is no deeper logic to learn here: it is history, so the safest plan is to know the split and avoid holes.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

45 Holes, and which methods ignore them

hard

A sparse array has slots that do not exist. Build one, then find out which methods skip the holes, which fill them in, and which drop them.

Stuck? Three hints, smallest first
  1. 1. [1, , 3], delete xs[1] and xs.length = 5 all produce holes.
  2. 2. i in xs is the test: a hole is absent, whereas a stored undefined is present.
  3. 3. map and forEach skip holes; Array.from and spread turn them into undefined.

Step 1: three ways to make a hole

Step 1

const literal = [1, , 3];

const deleted = [1, 2, 3];
delete deleted[1];

const stretched = [1, 2];
stretched.length = 4;

console.log(literal);   // [ 1, <1 empty item>, 3 ]
console.log(deleted);   // [ 1, <1 empty item>, 3 ]
console.log(stretched); // [ 1, 2, <2 empty items> ]

Node prints holes as empty item, and browser consoles show them as empty too. Notice that delete didn't shorten the array: deleted.length is still 3, with a hole in the middle. Setting length higher adds holes at the end.

Step 2: which keys really exist

Object.keys lists only the keys that exist, so holes are left out:

Step 2

console.log(Object.keys([1, , 3]));          // [ '0', '2' ]
console.log(Object.keys([1, undefined, 3])); // [ '0', '1', '2' ]

Step 3: the methods that skip holes

Step 3

const sparse = [1, , 3];

let visits = 0;
sparse.forEach(() => { visits++; });
console.log(visits); // 2

const mapped = sparse.map(() => 9);
console.log(mapped);      // [ 9, <1 empty item>, 9 ]
console.log(1 in mapped); // false

console.log(sparse.reduce((a, b) => a + b)); // 4

forEach ran its function twice, not three times. map didn't call its function for the hole, and the hole is still there in the new array. reduce added just 1 and 3. If it had visited the hole, the sum would have been NaN, because 1 + undefined is NaN.

Step 4: filter drops holes

Step 4

console.log([1, , 3].filter(() => true)); // [ 1, 3 ]

The test says "keep everything", yet the result is shorter. filter never offered the hole to the test, so it never got copied across.

Step 5: the methods that fill holes

Step 5

const filled = Array.from([1, , 3]);
console.log(filled);          // [ 1, undefined, 3 ]
console.log(1 in filled);     // true
console.log([...[1, , 3]]);   // [ 1, undefined, 3 ]

Array.from and spread read every index from 0 to length - 1. Reading a hole gives undefined, so the new array holds a real undefined there. The hole is gone.

Step 6: includes and indexOf disagree

Here the split shows up between two methods that look like twins:

Step 6

console.log([1, , 3].includes(undefined)); // true
console.log([1, , 3].indexOf(undefined));  // -1

includes is newer and treats the hole as undefined, so it finds it. indexOf is older and skips the hole, so it reports "not found".

Step 7: avoid holes in the first place

Step 7

console.log(Array.from({ length: 3 }, (_, i) => i * 10)); // [ 0, 10, 20 ]
console.log([1, 2, 3].filter((_, i) => i !== 1));         // [ 1, 3 ]
console.log([1, , 3].fill(0));                            // [ 0, 0, 0 ]

To make an array of a given size, use Array.from({ length: n }, ...) instead of new Array(n). To remove an item, use filter (or splice) instead of delete. If you are handed a sparse array, [...xs] turns the holes into undefined, and fill overwrites every slot. After that, every method agrees.

The full solution

The panel makes holes three ways, compares a hole with a stored undefined, and then runs each method on [1, , 3] so you can see which ones skip, fill or drop. Press Run and match each line to a step above.

The answer

const sparse = [1, , 3];                   // the middle slot does not exist
const deleted = [1, 2, 3];
delete deleted[1];                         // the same thing, made deliberately
const explicit = [1, undefined, 3];        // NOT sparse: three real values

let visits = 0;
sparse.forEach(() => { visits++; });

console.log('length     :', sparse.length, '<- the hole is counted');
console.log('1 in sparse:', 1 in sparse, ' 1 in explicit:', 1 in explicit);
console.log('Object.keys:', Object.keys(sparse), '<- only the real slots');
console.log('forEach visited', visits, 'of 3');
console.log('--- who skips, who fills, who drops ---');
console.log('map        :', [1, , 3].map(() => 9), 'hole kept?', !(1 in [1, , 3].map(() => 9)));
console.log('filter     :', [1, , 3].filter(() => true), '<- dropped');
console.log('Array.from :', Array.from([1, , 3]).map(String), '<- filled in');
console.log('spread     :', [...[1, , 3]].map(String), '<- filled in');
console.log('reduce     :', [1, , 3].reduce((a, b) => a + b), '<- skipped, so 4');

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('length counts the hole, but the slot is absent', [sparse.length, 1 in sparse], [3, false]);
test('while a stored undefined is present', 1 in explicit, true);
test('delete produces a hole rather than shortening the array', [deleted.length, 1 in deleted], [3, false]);
test('forEach never visits a hole', visits, 2);
test('map keeps the hole, so it stays absent', 1 in [1, , 3].map(() => 9), false);
test('filter removes holes altogether', [1, , 3].filter(() => true), [1, 3]);
test('Array.from fills them with real undefined values', 1 in Array.from([1, , 3]), true);
test('includes finds a hole as undefined, indexOf does not', [[1, , 3].includes(undefined), [1, , 3].indexOf(undefined)], [true, -1]);
test('and reduce skips it, so the sum is 4', [1, , 3].reduce((a, b) => a + b), 4);

The split runs along an old fault line. The methods from ES5 — map, forEach, filter, reduce, some, every, indexOf — were specified to skip absent indexes. The iteration-based ones added later — Array.from, spread, for...of, keys, includes, find, flat — treat a hole as undefined instead. There is no rule to derive; it is history.

Which is why the practical advice is to not have sparse arrays. Use filter instead of delete xs[i], and Array.from({ length: n }, ...) instead of new Array(n) followed by writes. If you inherit one, [...xs] or xs.fill() normalises it into real values first, and every method then agrees.

Common mistakes

  • Using delete to remove an item. It leaves a hole and keeps the length. Use filter or splice.
  • Testing for a hole with xs[i] === undefined. That is also true for a stored undefined. Use i in xs.
  • Creating arrays with new Array(n) and then calling map. map skips every hole, so nothing happens. Use Array.from({ length: n }, fn).

Try it yourself

  1. Call new Array(3).map(() => 'x') and explain the result.
  2. Write countHoles(xs) that returns how many indexes from 0 to length - 1 are missing.
  3. Loop over [1, , 3] with for...of and count how many times the body runs.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.