In summary: The first array contains holes, while the second one does not. When using .map
, it will skip over any holes present in the array.
When you use a spread element, the array is treated as an iterable, meaning you get an iterator to go through each value in the array. This iterator functions like a for
loop, iterating from index 0
to array.length - 1
. However, since your array has no values at these indices, array[i]
will return undefined
.
Therefore, [...new Array(3)]
results in an array with three instances of undefined
rather than just an empty array with length 3
.
If you observe this in Chrome, you can see the distinction:
https://i.sstatic.net/kbUqx.png
We refer to arrays with holes as "sparse arrays."
The key point: Several array methods, such as .map
, will ignore these holes! They do not treat the hole as simply an undefined value; instead, they disregard it entirely.
You can test this by adding a console.log
statement inside the .map
callback:
Array(3).map(() => console.log('call me'));
// no output
This explains why your initial example did not produce the expected outcome. The sparse array contained only holes, which were ignored by .map
. In contrast, creating a new array with the spread element eliminated the holes, allowing .map
to function correctly.