Quick and easy value clamping in JavaScript
Timothée Boucher
Posted on February 14, 2022
Ever needed to make sure a value stays within a certain range?
I've often written code like this:
function clamp (value, min, max) {
if (value > maximum) return maximum
if (value < minimum) return minimum
return value
}
let lower = clamp(9, 10, 25) // 10
let higher = clamp(30, 10, 25) // 25
let middle = clamp(22, 10, 25) // 22
Every time I see code like this, I know there's a way to do it with Math.max
and Math.min
but I'm always getting my wires crossed thinking about it.
So here it is:
function clamp (value, min, max) {
return Math.max(min, Math.min(max, value))
}
Next time, I just need to remember "max-min-min-max-value".
💖 💪 🙅 🚩
Timothée Boucher
Posted on February 14, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev JavaScript Higher-Order Functions Made Easy: Learn with a Real-Life Example! 💡
November 30, 2024