# Clamp numbers in JavaScript

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

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.

Basically, we cap a number to a segment.

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``````

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 checkout this codepen for the full code example.

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.

## ðŸ“– 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

• Games & Puzzles
• Fun & Interesting
• Tools & Libraries
• Personal & Portfolio
• Productivity
• Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X