Restrict Number to Min / Max Range
suggest changeclamp keeps a number inside a range. +val coerces the value first. If min is greater than max, the result is max. A non-numeric val becomes NaN.
function clamp(min, max, val) {
return Math.min(Math.max(min, +val), max);
}
console.log(clamp(-10, 10, "4.30")); // 4.3
console.log(clamp(-10, 10, -8)); // -8
console.log(clamp(-10, 10, 12)); // 10
console.log(clamp(-10, 10, -15)); // -10
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents