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

Alexandra picture Alexandra · Apr 30, 2011 · Viewed 71.9k times · Source

I want to limit a number between two values, I know that in PHP you can do this:

$number = min(max(intval($number), 1), 20);
// this will make $number 1 if it's lower than 1, and 20 if it's higher than 20

How can I do this in javascript, without having to write multiple if statements and stuff like that? Thanks.

Answer

Govind Malviya picture Govind Malviya · Apr 30, 2011

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")   )
)