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

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 can use the JavaScript array instance’s fill and map methods.

For instance, we write:

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

We can Array with 20 to create an array with 20 empty slots.

Then we call fill to fill the empty slots with undefined.

Finally, we call map with a callback to return the numbers from 1 to 20.

Therefore, arr is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20].

Conclusion

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