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.
Code
// 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 5How 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.