How to Clamp Numbers in JavaScript

How to Clamp Numbers in JavaScript

Ferenc Almasi β€’ πŸ”„ 2021 September 17 β€’ πŸ“– 2 min read

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
clamp.js
Copied to clipboard!
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

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
Copied to clipboard!

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
Copied to clipboard!

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);
clamp.js
Copied to clipboard!

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.

You should not extend native prototype, unless it is for compatibility reasons.
As stated in the Conclusion section on MDN (Inheritance & prototype chain)

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.

How to Clamp Numbers in JavaScript
If you would like to see more Webtips, follow @flowforfrank
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Resource

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access exclusive interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Remove ads to learn without distractions
Become a Pro

Recommended