To create array from for loop with JavaScript, we use the fill
and map
methods.
For instance, we write
const yearStart = 2000;
const yearEnd = 2040;
const years = Array(yearEnd - yearStart + 1)
.fill()
.map((_, i) => yearStart + i);
to create an array with length yearEnd - yearStart + 1
with Array
.
Then we call fill
to fill the empty slots with undefined
.
And then we call map
with a callback to map the undefined
values to yearStart + i
where i
is the index of the array currently being looped through.