Math.min and Math.max Clamp Values to Bounds

Bound values with Math.min and Math.max — empty calls return the infinities, any NaN poisons the result, and nesting the two builds a clamp.

JavascriptForm Validation

Code

javascriptsnippet
20 lines
// Math.min 和 Math.max 接受任意参数,返回最值
console.log(Math.min(3, 1, 4, 1, 5));
console.log(Math.max(3, 1, 4, 1, 5));

// 空参数:min 返回 Infinity,max 返回 -Infinity
console.log("empty min:", Math.min());
console.log("empty max:", Math.max());

// 任一参数为 NaN,结果就是 NaN(不静默忽略)
console.log("with NaN:", Math.min(1, NaN, 3));

// 展开数组做边界检查
const temps = [21, 19, 23, 18, 25];
console.log("range:", Math.min(...temps), "to", Math.max(...temps));

// 经典 clamp:用 min 和 max 把值限制在区间内
function clamp(value, lo, hi) {
  return Math.min(Math.max(value, lo), hi);
}
console.log("clamp:", clamp(15, 0, 10), clamp(-3, 0, 10), clamp(5, 0, 10));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

1
5
empty min: Infinity
empty max: -Infinity
with NaN: NaN
range: 18 to 25
clamp: 10 0 5

How the file is organized

The code’s whole job belongs to the function clamp.

Watch out for

  • No third-party code is loaded at any point while this runs.

Applying it

Signature: function clamp(value, lo, hi)

The demo output is labeled (empty min:, empty max:, with NaN:); each label names the call that printed it.

Statements that matter

return Math.min(Math.max(value, lo), hi);

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `clamp` at load time.