Either use .fill
:
const arr = new Array(5).fill(0);
console.log(arr);
or Array.from
, which has a built-in map function you can pass as a second parameter:
const arr = Array.from({ length: 5 }, () => 0);
console.log(arr);
See MDN:
map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).
Using Array.from
as above assigns undefined values to each element of the array, whereas new Array
does not, which is why you can map
after Array.from
but not after invoking the Array constructor.