Skip to content

clamp

The clamp() method limits a number within a given range. If the value is below the lower bound, it returns the lower bound. If it is above the upper bound, it returns the upper bound. Otherwise, it returns the value itself.

Interactive example

Syntax

Classic signature

typescript
function clamp<
	GenericInput extends number
>(
	input: GenericInput,
	lowerBound: number,
	upperBound: number
): number

Curried signature

typescript
function clamp<
	GenericInput extends number
>(
	lowerBound: number,
	upperBound: number
): (input: GenericInput) => number

Parameters

  • input: The number to clamp within the interval (classic signature only).
  • lowerBound: The lower bound of the interval.
  • upperBound: The upper bound of the interval.

Return value

returns a number clamped to the interval [lowerBound, upperBound]. If lowerBound and upperBound are inverted, the function automatically reorders them.

See also

  • max - Returns the maximum value
  • min - Returns the minimum value

Sources

Released under the MIT license.