Generating a Random Number
In JavaScript, you can get random number using Math.random( ) function. This function return a floating- point number from 0 (inclusive) to 1(exclusive).
JavaScript:
var randomNumber = Math.random();
console.log(randomNumber); //0.3039685388621798
This method generate a float number from 0 to 1, but we want a integer value so we use another method Math.floor( ) which convert float number into integer.
Math.floor( ) return a rounded down integer
JavaScript:
var randomNumber = Math.random() // 0.25428721717092606
randomNumber = randomNumber * 10; // 2.5428721717092606
randomNumber = Math.floor(randomNumber)
console.log(randomNumber); // 2
above method return a value from 0 to 9 but it did not return value of 10 (inclusive). if you want to value from 0 to 10. so you should Math.random() * 11 multiply by 11 and if you want to 1 to 10 so you have add 1 after Math.floor(Math.random() * 11) + 1;
JavaScript:
var randomNumber = Math.floor(Math.random() * 11) + 1;
console.log(randomNumber);
Get a random number from a specific range
to get random number from specific range, let's say from 5 to 10( both inclusive ), you should apply following code.
JavaScript:
let minVal = 5;
let maxVal = 10 + 1; // Adding 1 to include the maxVal
randomNumber = Math.floor(Math.random() * (maxVal - minVal ) ) + minVal;
console.log(randomNumber);
Math.random() generate a random number with uniform distribution.
In this method, Math.floor(Math.random() return a random number from 0 to 1, and then multiply by difference between maxValand minVal value . By flooring the result and adding by min . we obtain a random integer from 5 to 10.
Comments
Post a Comment