JAVASCRIPT RANDOM NUMBERS


The JavaScript as we have seen in JavaScript Math object methods, the Math.random() method is used to return a random number from 0 to 1 (1 not included).



Math.random(); //Returns a random number from 0 -> 1 (1 excluded)


Random Integers


The Math.random() and Math.floor() methods can be used together to return random integers.



Math.floor(Math.random() * 101); //Return a randowm number from 0 - 100

Live Demo!


Random Number Function


A random number function can be created to return a random number between specifies minimum and maximum number. In the above example, we can see that, the maximum number is not included in the range of numbers.



function generateRandomInteger(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

Live Demo!


We can add 1 to the max – min to change the function to return random numbers between the min and max number provided and with both the numbers included in the range.



function generateRandomInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

Live Demo!