Array(n)
creates an array of length n
, but the array has no values in it so there is nothing to map over.
Basically, this:
const a = Array(n);
is the same as:
const a = [];
a.length = n;
This is why the created array has no elements in it. Attempting to map it will do nothing since there are no values to map.
You can, however, convert that empty array to an array of undefined
values. This can be done in two ways:
One is using the spread operator as you have done:
[...Array(n)] // creates new array [undefined, undefined, undefined ...] n times
The other, more commonly used, is .fill()
, which sets its parameter as the value for all the indices of the array. To fill with undefined
, do:
Array(n).fill() // fills array with [undefined, undefined, undefined ...] n times
An array of undefined
, unlike an empty array, has elements and can therefore be mapped:
[undefined, undefined, undefined].map(x => 1) // [1, 1, 1]
So you can first convert your empty array to an array of undefined
, and then map it like so:
Array(n).fill().map(x => 1)
If you want to fill the array with the same element in each position like in this example, you can simply pass it in to fill without needing to map the array:
Array(n).fill(1)