There are multiple ways to create or fill an array with N numbers in JavaScript. Here I’m showing some of the most popular ways.
1. Using the fill() method
This is by far my favorite way whenever I want to generate some array with dummy or seed data.
const fooList = Array(10)
.fill()
.map((_, i) => i)
console.log(fooList)
//output
[0,1,2,3,4,5,6,7,8,9]
Code language: JavaScript (javascript)
In the code above, I’m populating the array with the following three steps:
- Array(10): To create an empty array of length 10. It’s value at this point is [ <10 empty items> ]
- Array(10).fill(): To fill the array with undefined values. It’s value at this point is [undefined, undefined, undefined …] 10 (times)
- Array(10).fill().map((_,i) => i): To map the undefined values with their index numbers and fill the array with it. It’s value at this point becomes [0, 1, 2, 3 … 9]
2. Using the spread operator
You can also use the spread operator and run a loop like the for loop to append the values to it’s last set of values:
let fooList = []
for (let i = 0; i < 10; i++) {
fooList = [...fooList, i]
}
console.log(fooList)
//output
[0,1,2,3,4,5,6,7,8,9]
Code language: JavaScript (javascript)
3. Using for loop and pushing the values
Or you can just do it the classic way using the good old for loop as shown below:
const fooList = []
for (let i = 0; i < 10; i++) {
fooList.push(i)
}
console.log(fooList)
//output
[0,1,2,3,4,5,6,7,8,9]
Code language: JavaScript (javascript)
Of course, there are more ways to do it, if you know of a better way, sound off in the comments below!