Lately I've been playing with number clamps, and I've found a few different ways to express the same behavior in JavaScript.

The idea of a number clamp is that if you're using a number that can change in value, you might want to set a minimum limit and maximum limit, and only use the variable number if it falls in the range between those two limits. In this situation, let's call the lower limit min, the number we're calculating as mid, and the upper limit as max.

  function ifClamp(min,mid,max){
  if (min < mid && mid < max) {
    return mid
  } else if (mid < min) {
    return min
  } else if (max < mid) {
    return max

This is legible, but a very verbose way to express it and it's not possible to grasp it quickly without reading the whole thing. The next way you could express this is by using two ternary statements, one nested inside the other:

  function ternaryClamp(min,mid,max){
  return mid < min ? min : mid < max ? mid : max

Same result can be achieved by using Math.min() and Math.max() to sort the three numbers in two steps:

  function mathClamp(min,mid,max){
  return Math.min(Math.max(min,mid),max)

Are there other ways that this same behavior can be expressed - and is there a better way to write this?

Examples of Live Number Clamps

1,219 1 2