DEV Community

Cover image for Quick and easy value clamping in JavaScript
Timothée Boucher
Timothée Boucher

Posted on • Updated on

Quick and easy value clamping in JavaScript

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
Enter fullscreen mode Exit fullscreen mode

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))
}
Enter fullscreen mode Exit fullscreen mode

Next time, I just need to remember "max-min-min-max-value".

Latest comments (0)