CyrefJS
CCyrefJS
فا
Back to documentation
Number/Since 1.38.0

clamp

Restricts a number to a specified inclusive range between a minimum and maximum value.

clamp(value, min, max):number

Parameters

valuenumberrequired

The number to restrict to the specified range.

minnumberrequired

The minimum allowed value.

maxnumberrequired

The maximum allowed value.

Returns

number

Returns 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

01

Basic usage

A value inside the range is returned unchanged.

TypeScript
console.log(clamp(5, 0, 10));
// 5
02

Value below minimum

Values below min are replaced with min.

TypeScript
console.log(clamp(-5, 0, 10));
// 0
03

Value above maximum

Values above max are replaced with max.

TypeScript
console.log(clamp(15, 0, 10));
// 10
04

Boundary values

The minimum and maximum values themselves are allowed.

TypeScript
console.log(clamp(0, 0, 10));
// 0

console.log(clamp(10, 0, 10));
// 10
05

Negative range

clamp also works with ranges containing negative numbers.

TypeScript
console.log(clamp(-15, -10, -5));
// -10

console.log(clamp(-7, -10, -5));
// -7

console.log(clamp(-2, -10, -5));
// -5
06

Equal minimum and maximum

When min and max are equal, the result is always that value.

TypeScript
console.log(clamp(5, 10, 10));
// 10

console.log(clamp(20, 10, 10));
// 10
07

NaN value

A NaN value is rejected with a RangeError.

TypeScript
clamp(NaN, 0, 10);
// RangeError: clamp: value must not be NaN
08

Invalid range

The function rejects a range where min is greater than max.

TypeScript
clamp(5, 10, 0);
// RangeError: clamp: min must be less than or equal to max
Built with@cyref/js·Official documentation