Coding Challenge - #31: Clamp Number Range

Write a function clamp(value, min, max) that restricts a given number to fall within an inclusive minimum and maximum range. For example, clamp(12, 0, 10) should return 10, clamp(-4, 0, 10) should return 0, and clamp(5, 0, 10) should return 5.

function clamp(value, min, max) {
  // your code here
}

Rules:

  • Must return the value itself if it falls within min and max
  • Must return min if value is less than min
  • Must return max if value is greater than max
  • Assume min is always less than or equal to max

Post your solution as a reply. Answer goes up in about a day.

The clamp function is deceptively simple but incredibly useful for things like animation loops or UI scaling, where you need values to stay within a visual boundary. My solution would handle the comparisons directly:

function clamp(value, min, max) {
  if (value < min) {
    return min;
  }
  if (value > max) {
    return max;
  }
  return value;
}
1 Like

Challenge solution: The challenge asks for a JavaScript function clamp(value, min, max) that restricts a number to a specified range.

One way to do it:

function clamp(value, min, max) {
  return Math.max(min, Math.min(value, max));
}

Why:
This solution uses Math.min to first ensure that value does not exceed max. The result of that operation is then passed to Math.max to ensure it is not less than min. This two-step process effectively clamps the value within the desired range.

First-answer leaderboard

  1. @emmawalter5 - 12 (firsts) :trophy:
  2. @kirupa - 8 (firsts)
  3. @Apexcodes - 6 (firsts)
  4. @adnanahmed - 2 (firsts)

A simple way is to use Math.min() and Math.max() together:

function clamp(value, min, max) {
  return Math.max(min, Math.min(value, max));
}

It keeps the value within the inclusive range. If it’s below min, it returns min; if it’s above max, it returns max. Otherwise, it returns the original value.

1 Like

That is a really good approach!

oh, thanks! it’s a useful function for many things I think.

@ArthurDent Nice one — I like how readable this is. The two early returns map straight onto the rules, low side then high side, and anything in between just falls through to return value. No clever tricks needed, and it’s the kind of version I’d actually want to come back to later and still understand at a glance.