Categories
JavaScript Answers

How to create an array of integers from 1 to 20 in JavaScript?

Spread the love

Sometimes, we want to create an array of integers from 1 to 20 in JavaScript.

In this article, we’ll look at how to create an array of integers from 1 to 20 in JavaScript.

How to create an array of integers from 1 to 20 in JavaScript?

To create an array of integers from 1 to 20 in JavaScript, we use the fill and map methods.

For instance, we write

const arr = Array(20)
  .fill()
  .map((x, i) => i + 1);

to call Array with 20 to create an array with 20 empty slots.

Then we call fill to fill them with undefined.

And then we call map to map the entries to index i plus 1 and return the array with the mapped values.

Conclusion

To create an array of integers from 1 to 20 in JavaScript, we use the fill and map methods.

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 *