How to make a random number generator JavaScript
This article looks at an example of a random number generator in JavaScript, using the standard Math.random() function.
Random Number Generator in JavaScript
Creating a random number generator in JavaScript involves using the Math.random() function and some simple math. 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.
Example
Here is an example of how to generate a random number in the range 0–10 using the Math.random() function:
// returns a random number between 0 and 10
function getRandomNumber() {
return Math.floor(Math.random() * 11);
}
This function will return a random number between 0 and 10, with an approximately equal probability of returning each of the 10 numbers.
If you wanted to generate a random number in the range 1–10, you can modify the function like this:
// returns a random number between 1 and 10
function getRandomNumber() {
return Math.floor(Math.random() * 10) + 1;
}
This function will return a random number between 1 and 10, with an approximately equal probability of returning each of the 10 numbers.