JavaScript Snippet

Clamp a Number Within a Range

Difficulty: Easy

Clamping a value into `[min, max]` shows up in scroll math, slider components, RGB arithmetic, and clamping pagination cursors. The one-liner is trivial, but the helpful version handles swapped bounds, `NaN`, and integer-only callers. This snippet covers the simple form, an `inclusive`/`exclusive` mapping flag, and an integer variant that snaps to whole numbers in the range.

Code Snippets
/

Clamp a Number Within a Range

Clamp a Number Within a Range

Clamping a value into `[min, max]` shows up in scroll math, slider components, RGB arithmetic, and clamping pagination cursors. The one-liner is trivial, but the helpful version handles swapped bounds, `NaN`, and integer-only callers. This snippet covers the simple form, an `inclusive`/`exclusive` mapping flag, and an integer variant that snaps to whole numbers in the range.

JavaScript
Easy
3 snippets
math
utility
code-template

199 views

4

Nesting Math.min and Math.max is the shortest clamp: max(value, min) lifts values below the floor, then min(...) against the ceiling caps anything above. The function is total over finite numbers and returns the value unchanged when it is already inside the range. NaN short-circuits both Math.min and Math.max to NaN, which is usually what you want (callers can detect and reject). One gotcha: if min > max, the function still runs but returns min, which silently masks a caller bug; the next accordion guards against that.