Clamp

easy
By FrontendAtlas Editorial · Updated Oct 10, 2026
Implement clamp(value, lower, upper) to keep a number within an inclusive range. If the value is below the lower bound, return the lower bound; if above the upper bound, return the upper bound. This is a tiny but common utility for sliders, percentages, and animations. Concepts: numbers, math, boundaries, utilities.

Arguments

  • value: number — The number to clamp.
  • lower: number — The lower bound.
  • upper: number — The upper bound.

Returns

number — The clamped number.

Solution idea

Clamp is a three-branch check that guarantees a value stays inside [lower, upper]. It is intentionally simple and predictable: values below the range snap to the lower bound, values above snap to the upper bound, and in-range values are returned unchanged. Key concepts: numbers, math, boundaries.

Examples
// Basic examples
clamp(3, 0, 5) // => 3
clamp(-10, -3, 5) // => -3
clamp(10, -5, 5) // => 5

// On the bounds (inclusive)
clamp(0, 0, 5) // => 0
clamp(5, 0, 5) // => 5