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)

How the Logic Works

Under the hood, _.clamp evaluates the input against the specified limits using standard comparison operations. The logic follows these steps:

  1. Upper Bound Check: The number is compared against the upper bound. If number > upper, the value is set to upper.
  2. Lower Bound Check: The resulting value is compared against the lower bound. If number < lower, the value is set to lower.
  3. Range Preservation: If the number is greater than or equal to lower and less than or equal to upper, 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 -50

Common Use Cases

_.clamp simplifies common boundary-checking logic across various scenarios:

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.