How Lodash rangeRight Works in JavaScript
The Lodash _.rangeRight method is a utility function
designed to produce an array of numbers in descending order. While it
accepts the same arguments as the standard _.range
method—start, end, and step—it
reverses the population order of the resulting array. This article
breaks down the syntax, internal mechanics, and practical examples of
how _.rangeRight generates descending numerical
sequences.
Syntax and Parameters
The method signature for _.rangeRight is:
_.rangeRight([start=0], end, [step=1])start(number, optional): The start of the range. Defaults to0if only one argument is supplied.end(number): The end of the range. This value is exclusive.step(number, optional): The value to increment or decrement by. Defaults to1(or-1ifendis less thanstart).
How
_.rangeRight Generates Descending Sequences
Under the hood, _.rangeRight uses the exact same
calculation as _.range to determine the values included in
the sequence, but it alters the order in which they are populated into
the array.
Instead of filling the array from start up to
end, _.rangeRight calculates the sequence
bounds and fills the elements from the end toward the beginning. Because
the end boundary in range functions is exclusive, the
highest generated value will always be one step interval
away from the end boundary, while the start
value will appear at the end of the array.
Practical Examples
1. Single Argument (End Only)
When provided with a single argument, the start defaults
to 0 and step defaults to 1. The
values generated are from 0 to end - 1, output
in descending order:
_.rangeRight(4);
// => [3, 2, 1, 0]2. Specifying Start and End
When both start and end are provided, the
sequence starts from the highest allowable step below end
and stops at start:
_.rangeRight(1, 5);
// => [4, 3, 2, 1]3. Using a Step Value
Adding a step value increments the calculation by that value.
_.rangeRight still produces the final array in reverse:
_.rangeRight(0, 20, 5);
// => [15, 10, 5, 0]4. Handling Negative Values
If start is greater than end and a negative
step is used (or inferred), the direction of the range naturally moves
negative, and _.rangeRight outputs the reverse of that
negative progression:
_.rangeRight(0, -4, -1);
// => [-3, -2, -1, 0]Key Differences from
_.range().reverse()
While _.range(start, end, step).reverse() produces the
same output as _.rangeRight(start, end, step),
_.rangeRight is more performant. It directly allocates the
memory and populates the indices from right to left rather than creating
an ascending array in memory and executing a separate reversal
operation.