Lodash inRange When Start Is Greater Than End
This article explains how the Lodash _.inRange function
behaves when a starting integer is intrinsically larger than its ending
integer. It covers Lodash’s internal parameter normalization, the
automatic swapping mechanism used to support reverse ranges, and how
boundary inclusivity and exclusivity are enforced during evaluation.
When _.inRange(number, start, end) is called with a
start argument that is numerically greater than the
end argument, Lodash does not throw an error or fail the
validation. Instead, the function detects this inversion and
automatically swaps the values of start and
end.
Lodash implements this behavior to natively support descending and
negative ranges. Under the hood, Lodash normalizes the bounds so that
the smaller integer serves as the minimum threshold and the larger
integer serves as the maximum threshold. In core implementations, this
is handled either by swapping the variable references when
start > end or by evaluating the boundaries using
Math.min(start, end) and
Math.max(start, end).
The standard boundary rules of _.inRange still strictly
apply after the values are swapped:
- The lower bound (the smaller value) is inclusive
(
>=). - The upper bound (the larger value) is exclusive
(
<).
For example, calling _.inRange(3, 5, 1) triggers the
swap logic. Lodash normalizes the lower bound to 1 and the
upper bound to 5. The condition evaluated is whether
3 >= 1 && 3 < 5, which evaluates to
true.
Because of this swap, boundary conditions must be noted:
- Testing the smaller integer (e.g.,
_.inRange(1, 5, 1)) returnstruebecause the minimum bound is inclusive. - Testing the larger integer (e.g.,
_.inRange(5, 5, 1)) returnsfalsebecause the maximum bound is exclusive.
Prior to swapping, Lodash coerces both arguments to numbers. If
either argument is non-numeric and resolves to NaN, the
function bypasses the swap comparison and returns false.
When valid integers are supplied, the swap validation ensures consistent
range checks regardless of argument order.