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
clamp.js
Copied to clipboard!
Learn JavaScript with Udemy

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:


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

Resource

πŸ“š Get access to exclusive content

Want to get access to exclusive content? Support webtips to get access to tips, checklists, cheatsheets, and much more. β˜•

Get access Support us
Read more on
πŸŽ‰ Thank you for subscribing to our newsletter. x