For more tips like this, sign up to the weekly newsletter!

How to create a range of numbers

To create an array containing the numbers 0...N - 1, there are several options.

The traditional approach is to use a for loop:

const result = [];
for (let i = 0; i < N; i++) {
  result.push(i);
}

For N = 5, result will be [0, 1, 2, 3, 4].

It works, but it's far from being short or expressive. Fortunately, there are a few options to choose from that remedy these shortcomings.

Use a library

Several libraries provide this functionality in the form of a function call:

ImmutableJS returns a Seq containing an array, while the other two return a native Array. To convert a Seq to a JS array, use .toArray().

Use some ES6 magic

There are many solutions for a one-liner, but the one I find the best regarding readability, versatility, and length is:

Array(N).fill().map((e, i) => i)
How does it work?

Array(N) creates an array with a length of N.

But it does not set the elements, only the length. This is a strange behavior and can lead to errors, as iteration is over the elements. For example,

Array(5).forEach((e) => console.log(e));

prints nothing!

This is why the next part, .fill() is needed. It sets all the elements to a given value, in this case, undefined. In a sense, fill() fixes Array(N).

Therefore, Array(N).fill() creates an array with N undefined elements.

Finally, iterate over it, and set the element to the index. This replaces the undefineds with 0, 1, ... N - 1.

This structure also gives you some flexibility. For example, to construct a range of numbers from start to end - 1, use

Array(end - start).fill().map((e, i) => start + i)
Try it
References
Learn more: