The Math.random() method returns a random number between 0
(inclusive), and 1 (exclusive). This is the foundation for all randomness in JavaScript,
from games to security tokens.
Math.random() always returns a fractional number (a decimal).
Math.random(); // returns something like 0.743219...
To get a whole number (an integer), you must combine Math.random() with
Math.floor(). Multiplying by a number sets the upper limit.
// Returns a random integer from 0 to 9:
Math.floor(Math.random() * 10);
// Returns a random integer from 0 to 10:
Math.floor(Math.random() * 11);
// Returns a random integer from 1 to 10:
Math.floor(Math.random() * 10) + 1;
Instead of writing the math every time, it is best practice to use a reusable function that takes a minimum and maximum value.
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
This function will return a random number between min (included) and
max (excluded).
max value to be
included as well, use (max - min + 1) in the multiplication.
Math.random() returns a decimal between 0 and 0.999...
Math.floor() to convert decimals to integerscrypto.getRandomValues() instead of Math.random()