How can I use JavaScript to limit a number between a min/max value?

Solution 1:

like this

var number = Math.min(Math.max(parseInt(number), 1), 20);

Live Demo:

function limitNumberWithinRange(num, min, max){
  const MIN = min || 1;
  const MAX = max || 20;
  const parsed = parseInt(num)
  return Math.min(Math.max(parsed, MIN), MAX)
}

alert(
  limitNumberWithinRange(  prompt("enter a number")   )
)

Solution 2:

You have at least two options:

You can use a pair of conditional operators (? :):

number = number > 100 ? 100 : number < 0 ? 0 : number;

Or you can combine Math.max and Math.min:

number = Math.min(100, Math.max(0, number));

In both cases, it's relatively easy to confuse yourself, so you might consider having a utility function if you do this in multiple places:

function clamp(val, min, max) {
    return val > max ? max : val < min ? min : val;
}

Then:

number = clamp(number, 0, 100);

Solution 3:

Use lodash's clamp method:

_.clamp(22, 1, 20) // Outputs 20