šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

Clamp numbers in JavaScript

By clamp, we are referring to a way to restrict the value of a JavaScript number between two other numbers.

Basically, we cap a number val to the bounds of the segment [min, max].

For example:

clamp(10, 50 /* min */, 100 /* max */) // returns 50
clamp(20, 1 /* min */, 15 /* max */) // returns 15
clamp(8, 4 /* min */, 12 /* max */) // returns 8

This means that when clamped, a number will:

  • keep its own value if it fits in the range imposed by min and max
  • take the value min if it is lower than it
  • or take the max value if is higher than it.

To implement a number clamping function in JavaScript we can mix the Math.min() and Math.max() functions:

/**
 * Returns a number whose value is limited to the given range.
 *
 * @param {Number} val The initial value
 * @param {Number} min The lower boundary
 * @param {Number} max The upper boundary
 * @returns {Number} A number in the range (min, max)
 */
const clamp = (val, min, max) => Math.min(Math.max(val, min), max)

clamp(-10, 20, 30) // returns 20
clamp(25, 20, 30)  // returns 25
clamp(500, 20, 30) // returns 30

Clamp numbers in JavaScript

If needed, one nice addition we can make to this function is to provide some default values for the min and max parameters:

const clamp = (val, min=1, max=10) => Math.min(Math.max(val, min), max)

clamp(5) // returns 5
clamp(-3) // returns 1

You can check out the full code my Github repository and see the live example here.

As a side note, we also have a clamp() function directly build into CSS.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *