1.38.0clamp
Restricts a number to a specified inclusive range between a minimum and maximum value.
clamp(value, min, max):numberParameters
valuenumberrequiredThe number to restrict to the specified range.
minnumberrequiredThe minimum allowed value.
maxnumberrequiredThe maximum allowed value.
Returns
numberReturns the value constrained to the inclusive range from min to max.
Errors
Throws a RangeError if value is NaN.
Throws a RangeError if min or max is NaN.
Throws a RangeError if min is greater than max.
Examples
Basic usage
A value inside the range is returned unchanged.
console.log(clamp(5, 0, 10));
// 5Value below minimum
Values below min are replaced with min.
console.log(clamp(-5, 0, 10));
// 0Value above maximum
Values above max are replaced with max.
console.log(clamp(15, 0, 10));
// 10Boundary values
The minimum and maximum values themselves are allowed.
console.log(clamp(0, 0, 10));
// 0
console.log(clamp(10, 0, 10));
// 10Negative range
clamp also works with ranges containing negative numbers.
console.log(clamp(-15, -10, -5));
// -10
console.log(clamp(-7, -10, -5));
// -7
console.log(clamp(-2, -10, -5));
// -5Equal minimum and maximum
When min and max are equal, the result is always that value.
console.log(clamp(5, 10, 10));
// 10
console.log(clamp(20, 10, 10));
// 10NaN value
A NaN value is rejected with a RangeError.
clamp(NaN, 0, 10);
// RangeError: clamp: value must not be NaNInvalid range
The function rejects a range where min is greater than max.
clamp(5, 10, 0);
// RangeError: clamp: min must be less than or equal to max