Sometimes, you want to render a sequence of numbers. For example, the pagination widget at the bottom of Google search results:
Perhaps even more commonly, you want to render something a handful of times. Maybe you want to generate 5 particles, or a bunch of background lines for a graph.
In React, this matter is complicated a bit, because we need an array we can map over. Essentially, I want to be able to do something like this:
I'm not able to use a
for loop, since we need to render expressions within JSX.
range utility gives me a concise, functional way to solve for these kinds of problems.
This utility can be used in several ways.
You can pass a single number, to generate a range from 0 through that number:
You can pass two numbers, to generate a range from start to finish:
Finally, you can pass a third "step" argument, if you want to change the gap between numbers:
You'll notice that the array produced is inclusive of the starting number, but exclusive of the ending number.
Iterating from a start value to an end value, with a given step, is exactly the problem that
for loops were designed to solve. Our
range function is really just a thin wrapper around this common "vanilla" pattern!
One possibly surprising bit is this:
This check exists so that we can call
range with a single value, like
range(4). Instead of being used as the
start value, we're copying this value to
end, and setting
start to 0. This is a quality-of-life thing, to make it a small bit easier to use.