whatstheoutput_

#63: forEach vs map on a sparse array

Topic: arrays · Difficulty: ★★

const arr = [1, , 3];
let count = 0;
arr.forEach(() => count++);
console.log(count);
console.log(arr.map(x => x * 2));

Output

2
[ 2, <1 empty item>, 6 ]

Why

The array literal [1, , 3] has a genuine hole at index 1 — the extra comma leaves that slot empty rather than setting it to undefined. forEach() explicitly skips holes: it never invokes its callback for indices that don't exist, so the counter only increments twice (for index 0 and index 2), even though arr.length is 3. map() ALSO skips calling its callback on holes — the doubling function never runs on index 1 — but map() still preserves that index as a hole in the RESULT array to keep the output the same length and shape as the input, which is why the printed array shows an empty slot in the middle rather than a doubled undefined.

More arrays puzzles

Play today's puzzle →