Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to limit a number to a range

Short answer

Math.max() raises the number to the minimum, and Math.min() lowers it to the maximum:

const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
 
console.log(clamp(150, 0, 100));
console.log(clamp(-5, 0, 100));
console.log(clamp(42, 0, 100));

Output:

100
0
42

Wrapping around

Sometimes a value should wrap around instead, like slide numbers in a gallery. The remainder operator helps:

const count = 5;
const wrap = (index) => ((index % count) + count) % count;
 
console.log(wrap(5), wrap(-1), wrap(7));

Output:

0 4 2

Common mistake

The order matters: if you swap min and max in the formula, the result is always the minimum:

const wrongClamp = (value, min, max) => Math.max(Math.min(value, min), max);
 
console.log(wrongClamp(50, 0, 100));

Output:

100

Functions used in this recipe

  • Math.min — Returns the smallest of the given numbers.
  • Math.max — Returns the largest of the given numbers.

Thanks for reading!

Donate to the site — we work hard for you.