Categories
JavaScript Answers

How to generate range of numbers from 0 to n in JavaScript ES2015 only?

Spread the love

Sometimes, we want to generate range of numbers from 0 to n in JavaScript ES2015 only.

In this article, we’ll look at how to generate range of numbers from 0 to n in JavaScript ES2015 only.

How to generate range of numbers from 0 to n in JavaScript ES2015 only?

To generate range of numbers from 0 to n in JavaScript ES2015 only, we can use the array keys method.

For instance, we write

const nums = [...Array(n).keys()];

to use Array(n) to get an array with n empty slots.

Then we call keys on it to get the indexes of the array in an array.

Next, we use the spread operator to spread the indexes into a new array.

Conclusion

To generate range of numbers from 0 to n in JavaScript ES2015 only, we can use the array keys method.

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 *