Lodash _.clamp: Restrict Numbers in JavaScript
The _.clamp method in the Lodash JavaScript library is a
utility function designed to restrict a given number within inclusive
lower and upper boundaries. If the target number falls within the
specified range, the method returns the number unchanged; if it falls
below the minimum, it returns the lower bound; and if it exceeds the
maximum, it returns the upper bound. This article breaks down the
syntax, internal evaluation logic, and practical applications of
_.clamp.
Syntax and Parameters
The signature for the _.clamp method is:
_.clamp(number, [lower], upper)number(number): The initial value to clamp.[lower](number): The lower boundary (minimum allowed value).upper(number): The upper boundary (maximum allowed value).
How the Logic Works
Under the hood, _.clamp evaluates the input against the
specified limits using standard comparison operations. The logic follows
these steps:
- Upper Bound Check: The number is compared against
the
upperbound. Ifnumber > upper, the value is set toupper. - Lower Bound Check: The resulting value is compared
against the
lowerbound. Ifnumber < lower, the value is set tolower. - Range Preservation: If the number is greater than
or equal to
lowerand less than or equal toupper, the original number is returned.
If only two arguments are
supplied—_.clamp(number, upper)—Lodash treats the second
argument as the upper boundary and skips the lower boundary check.
Code Examples
Standard Clamping
const _ = require('lodash');
// Number is within the range: returns 5
_.clamp(5, 0, 10);
// Number is below the lower bound: returns 0
_.clamp(-5, 0, 10);
// Number exceeds the upper bound: returns 10
_.clamp(15, 0, 10);Clamping with Upper Bound Only
When passing only two arguments, _.clamp enforces only
the maximum threshold:
// Restricts value to a maximum of 100
_.clamp(120, 100); // Returns 100
_.clamp(-50, 100); // Returns -50Common Use Cases
_.clamp simplifies common boundary-checking logic across
various scenarios:
- UI Controls and Sliders: Keeping scroll positions,
zoom levels, or volume sliders between predefined minimums and maximums
(e.g., between
0and100). - Pagination: Preventing current page indicators from
dropping below page
1or exceeding the total page count. - Game Development: Constraining character coordinates to ensure sprites remain within the screen or map boundaries.
Native Alternative
In modern JavaScript without Lodash, the equivalent behavior is
achieved by combining Math.min and
Math.max:
const clamp = (num, min, max) => Math.min(Math.max(num, min), max);While the native approach works cleanly, _.clamp
provides a more readable and self-documenting syntax that eliminates the
common nested Math.min(Math.max(...)) pattern.