Categories
JavaScript Answers

How to iterate over range in a functional way with JavaScript?

Spread the love

Sometimes, we want to iterate over range in a functional way with JavaScript.

In this article, we’ll look at how to iterate over range in a functional way with JavaScript.

How to iterate over range in a functional way with JavaScript?

To iterate over range in a functional way with JavaScript, we use the array keys method.

For instance, we write

const arr = [...Array(20).keys()].map((i) => i * i);

to create an array with 20 empty slots with Array(20).

Then we call keys to return an array of indexes of the array.

And then we call map with a callback to map the index i to i squared.

Conclusion

To iterate over range in a functional way with JavaScript, we 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 *