To achieve this, you have two options:
const array = new Array(5).fill(0);
console.log(array);
Alternatively, you can use Array.from
with a custom mapping function:
const array = Array.from({ length: 5 }, () => 0);
console.log(array);
For more information, refer to the MDN documentation:
The map function iterates through elements in an array, applies a callback function, and generates a new array based on the returned values. It only runs the callback on elements with assigned values, including undefined. Elements that are missing, deleted, or never assigned a value are not processed.
When using Array.from
, undefined values are assigned to array elements. This differs from using new Array
, which does not assign undefined values, making it possible to apply map
after using Array.from
but not after using the Array constructor directly.