Categories
JavaScript Answers

How to create array from for loop with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *