
How to Clamp Numbers in JavaScript
Use the following function in JavaScript to easily clamp numbers between a min and a max value:
const min = 0;
const max = 100;
// Clamp number between two values with the following line:
const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
clamp(-50, min, max); // Will return: 0
clamp(50, min, max); // Will return: 50
clamp(500, min, max); // Will return: 100

Explanation
Let's break this code down to fully understand what is going on. You start with a number, and min and max values. Let's say the number you want to cap is 50, your min is 0, and your max is 100. You pass your number to Math.max
, along with your min value:
Math.max(50, 0); // -> 50
This will return the higher number from the two, which means you get 50 back. You then pass this to Math.min
along with your max value:
Math.min(50, 100); // -> 50
This time, this will return the lowest number from the passed arguments. Hence:
- If value < min, it will return the minimum allowed number
- If value > max, it will return the maximum allowed number
- If value > min and value < max, it will return the passed number
Support
Using the same function, you could make it global by extending the Number object:
Number.prototype.clamp = (num, min, max) => Math.min(Math.max(num, min), max);
(-50).clamp(-50, min, max);
(50).clamp(50, min, max);
(500).clamp(500, min, max);
However, keep in mind this is considered to be a bad practice and should be avoided. Only use it if you need compatibility with newer features.

Instead, if you use a modern framework, you can simply include it at the root of your project or store it in a global namespaced object. (eg.: app.utils.clamp
)
There is also a proposal for a built in Math.clamp
function, however, it is still in draft. Until it gets widely adopted, you need to polyfill it.


Resource
Access exclusive interactive lessons
Unlimited access to hundreds of tutorials
Remove ads to learn without distractions