A Quick Guide to Clamping Numbers in JavaScript

marileon

Omari

Posted on February 8, 2024

A Quick Guide to Clamping Numbers in JavaScript

In JavaScript, there’s “Math.min()”, “Math.max()”, but unfortunately no Math.clamp(). There’s but it’s currently in the draft stages. This is fine — it’s very easy to implement clamp, and in this article, I’ll talk through doing just that.

A Quick Way

You can use the following function to clamp a number between a minimum and maximum value:

function clamp(num: number, lower: number, upper: number) {
    return Math.min(Math.max(num, lower), upper);
}
Enter fullscreen mode Exit fullscreen mode

Why does this work? Let’s think it through. At first, our number is any valid JavaScript number, anything in the range -Number.MAX_VALUE <= num <= Number.MAX_VALUE

Then we have:

Math.max(num, lower);
Enter fullscreen mode Exit fullscreen mode

So now our range gets updated to whatever the larger value is out of “lower” and “num”. Our range is now: lower <= num <= Number.MAX_VALUE.

I’m sure you can see where this is going — let’s break our code up:

const lowerBound = Math.max(num, lower);
const result = Math.min(num, upper);
Enter fullscreen mode Exit fullscreen mode

Just like before but reversed. Our result is the lower of num or upper, so we can update our range to: lower <= num <= upper.

And just like that, our number is clamped! If it’s lower than the lower bound, we pick the lower bound. If it’s higher than the upper bound, we pick the upper bound. Otherwise, we pick the number.

Lodash

Lodash is a JavaScript utility library. You can install it with one of these commands:

npm i lodash 
pnpm add lodash 
yarn add lodash
Enter fullscreen mode Exit fullscreen mode

And it works exactly the same as our function:

import { clamp } from 'lodash'; 
clamp(number, lower, upper);
Enter fullscreen mode Exit fullscreen mode

Short and simple! If you’re not familiar with Lodash, it can be quite handy if you’re looking for any functions not native to JavaScript. Check it out .

Conclusion

So there’s two ways of getting the clamp math function into your JavaScript code. Which one should you use? Personally, I think since it’s such a small function, you should probably just implement this one yourself if you need it. If you’re already using Lodash though, then you may as well use their built-in function. Thanks for reading! If you liked this article, why not follow me on Twitter?

Originally published at https://www.omarileon.me.

💖 💪 🙅 🚩
marileon
Omari

Posted on February 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related