javascript restrict number to range 1

javascript restrict number to range

// Restricts number from 20 to 1 
// if number > 20 returns 20
// if number < 1 returns 1
// else returns number
var number = Math.min(Math.max(parseInt(number), 1), 20);

Here is what the above code is Doing:
1. We're using the parseInt() function to convert the string to an integer.
2. We're using the Math.min() function to restrict the number to a minimum of 1.
3. We're using the Math.max() function to restrict the number to a maximum of 20.

Similar Posts