How Lodash inRange Checks Number Intervals

Lodash's _.inRange method is a utility function used to verify whether a given number falls between two specified boundary values. This article explains the internal mechanics of _.inRange, including its parameter handling, how it evaluates boundaries using a half-open interval, and how it automatically resolves inverted or omitted arguments.

Syntax and Core Evaluation Rule

The syntax for the method is defined as:

_.inRange(number, [start=0], end)

The function checks whether the target number satisfies the condition:

\[\text{start} \le \text{number} < \text{end}\]

In mathematical terms, _.inRange operates on a half-open interval, denoted as [start, end). The lower boundary (start) is inclusive, while the upper boundary (end) is exclusive. If the evaluated number is equal to start, the function returns true. If the number is equal to end, it returns false.

_.inRange(3, 2, 4); // true (2 <= 3 < 4)
_.inRange(2, 2, 4); // true (inclusive of start)
_.inRange(4, 2, 4); // false (exclusive of end)

Default Parameter Handling

When only two arguments are supplied to _.inRange, the function alters the parameter assignments. Lodash sets the start value to 0, and the second argument is treated as the end boundary:

_.inRange(3, 4); // true, evaluated as _.inRange(3, 0, 4)
_.inRange(-1, 4); // false, -1 is less than 0

This behavior simplifies zero-based index and threshold checks without requiring an explicit 0 argument.

Automatic Boundary Swapping

If the provided start value is greater than the end value, _.inRange automatically swaps the boundaries to maintain standard numeric evaluation rather than returning an inverted or impossible range check:

_.inRange(3, 4, 2); // true, swapped internally to _.inRange(3, 2, 4)
_.inRange(2, 4, 2); // true (inclusive of minimum boundary 2)
_.inRange(4, 4, 2); // false (exclusive of maximum boundary 4)

Internally, Lodash normalizes the bounds using minimum and maximum calculations:

const min = Math.min(start, end);
const max = Math.max(start, end);

return number >= min && number < max;

This ensures consistent behavior across both positive and negative sequences, making _.inRange a predictable method for boundary validation in JavaScript applications.