Regarding Array constructor
All these calls are equivalent:
Array(2)
new Array(2)
var a = []; a.length = 2
They are equal in a sense that they allocate memory for assignment, but don't create the indexes.
Object.keys(Array(2)) // []
.
That's why when you do
Array(2).map(() => 1); // [undefined × 2]
you essentially change nothing, because no iteration happens over the array, because of lack of iteration index keys that map
uses while iterating over the array.
Regarding spread operator
...
operator calls the [Symbol.iterator]
of an array which is the built in values()
iterator and iterates over values even with absent key indexes.
That is why in the outcome we have a new array with distinct undefined values with key indexes in place.
Object.keys([...Array(2)]) // ["0", "1"]
.
After which map
works as expected iterating over the keys and corresponding values.