Math.random() is probably the most frequently-used source of randomness in Javascript. However a halo of mystery surrounds it and generates confusion especially in beginners.
From the Mozilla Developer Network documentation:
“The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.”
Math.random() can be used to get a random number between two values. The returned value is no lower than min and may possibly be equal to min, and it is also less than and not equal to max.
For getting a random number between two values the math.random() function can be executed in the following way:
// Returns a random integer between min (include) and max (include)
function randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
Some usage example
// 0 -> 10
Math.floor(Math.random() * 11);
// 1 -> 10
Math.floor(Math.random() * 10) + 1;
// 5 -> 20
Math.floor(Math.random() * 16) + 5;
// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;
Want to know more?
In V8 and most other Javascript engines, it is implemented using a pseudo-random number generator (PRNG).