...and Array.fill() comes to the rescue!
Used to write it all manually before knowing this one ♂️
Array(5).fill('') // => ['','','','','']
Array(4).fill(0) // => [0, 0, 0, 0]
You can also easily create a sequential array using fill() + map()
Array(4).fill('').map((_, i) => i + ' ') // => ['0 ','1 ','2 ','3 ']
Array(3).fill(' ').map((flower, i) => i + flower) // => ['0 ','1 ','2 ']
❗️Just be careful when creating objects and arrays using .fill() as they are referenced types❗️
That means Javascript will consider all the created items as being the same object (what may introduce unexpected bugs in case you want to further interact with the created objects)
// ❌ Careful when using .fill() with objects and arrays:
Array(3).fill({ value: 2 }) // => [{ value: 2 },{ value: 2 },{ value: 2 }]
The above line works, but it would be much safer to stick to the .fill().map() pattern. Like this:
// Much better!
Array(3).fill().map(item => ({ value: 2 }))