JavaScript clamp: limit a number between min and max
By StringClass ยท Published
For finite numbers with low <= high, use Math.min(high, Math.max(low, value)). This preserves values inside the interval and returns the nearest boundary outside it.
Before you start: You can write a JavaScript function and use numeric comparisons. No packages or build tools are needed for the JavaScript examples.
Try the JavaScript example
Change the value or its bounds, or edit the function. Run it to see the returned number. Values must be finite numbers and the lower bound must not exceed the upper bound.
Use Tab to move between controls. Code runs in an isolated browser workspace. Edits stay on this page until you leave or reset it.
Ready to run
Run the example to see its output here.
The clamp function
Clamping keeps a number inside an inclusive interval. A volume control might accept values from 0 to 100: a requested volume of 120 becomes 100, while 42 stays 42. Clamping does not round a fraction, wrap around to the other end, or convert units.
This function assumes all three arguments are finite numbers and low <= high:
function clamp(value, low, high) {
return Math.min(high, Math.max(low, value));
}
console.log(clamp(120, 0, 100)); // 100
console.log(clamp(42, 0, 100)); // 42
console.log(clamp(-8, 0, 100)); // 0
Run this in a browser console or Node.js. JavaScript's Math methods need no import. This is a numeric helper; it does not change the size or appearance of an element like CSS clamp() does.
Why it works
Read from the inner expression outward. Math.max(low, value) chooses whichever is larger, so its result cannot be below the lower bound. Math.min(high, ...) caps that result at the upper bound.
For clamp(120, 0, 100), the intermediate result is Math.max(0, 120), or 120. The outer operation chooses Math.min(100, 120), or 100. For a value already inside the range, neither operation changes it.
The equivalent branches can be easier to debug:
function clampWithBranches(value, low, high) {
if (value < low) return low;
if (value > high) return high;
return value;
}
Both versions take constant time and constant extra space. Keep the same argument order everywhere: value, then the lower limit, then the upper limit.
Boundary cases
Both endpoints are valid results. Equal limits describe a single allowed value, and negative intervals work in the same way as positive ones.
| Expression | Result | Reason |
|---|---|---|
clamp(0, 0, 10) |
0 | Lower endpoint is included |
clamp(10, 0, 10) |
10 | Upper endpoint is included |
clamp(1.5, 0, 2) |
1.5 | Fractions are preserved |
clamp(-3, -5, -1) |
-3 | Value is inside a negative interval |
clamp(8, 2, 2) |
2 | Only one result is allowed |
Test properties as well as examples: the result must be at least low, at most high, and equal to value whenever the input was already in range. Clamping an already clamped value should leave it unchanged.
Validate external input
The short formula assumes valid arguments. It does not validate form fields: an HTML input's value is text, and empty text should not silently become a meaningful quantity. Math.min and Math.max can coerce strings; NaN propagates through the formula. Reversed limits violate the contract.
If your function accepts data from another part of an application, check the contract at that boundary:
function clampFinite(value, low, high) {
if (![value, low, high].every(Number.isFinite)) {
throw new TypeError("Expected three finite numbers");
}
if (low > high) {
throw new RangeError("low must be less than or equal to high");
}
return Math.min(high, Math.max(low, value));
}
This version rejects numeric strings, NaN, and infinities. Parse and validate user input separately according to the application's rules. Silently swapping reversed bounds can hide a calling mistake, so this version reports it instead.
TypeScript version
Adding annotations describes the function to the type checker:
function clamp(value: number, low: number, high: number): number {
return Math.min(high, Math.max(low, value));
}
TypeScript's number includes NaN and infinities. Annotations also cannot prove low <= high. Use runtime validation when those properties are not already guaranteed. The related StringClass exercise uses TypeScript and the finite, ordered-input contract.
Try it yourself
Before running the following calls, predict their answers. Then run them with the first JavaScript function above.
console.log(clamp(-12, -10, -2)); // -10
console.log(clamp(0.25, 0, 1)); // 0.25
console.log(clamp(99, 4, 4)); // 4
Next, write the branch version without looking back. Check a value below the range, both exact endpoints, a value inside, a value above, and equal bounds. If you add validation, verify that an empty string and reversed bounds are rejected.
References: MDN Math.min and MDN Math.max describe the underlying numeric operations.