When building games, animations, or any application that requires unpredictable behavior, generating random numbers is essential.
JavaScript provides the built-in Math.random() method exactly for this purpose. However, using it correctly requires combining it with other Math methods. Let's explore how it works!
Math.random()The Math.random() method returns a random floating-point (decimal) number.
0 (inclusive).1 (exclusive).// Generates a random number like 0.4352123512... let randomNum = Math.random(); console.log(randomNum);
While getting a decimal between 0 and 1 is mathematically useful, most of the time developers want a random whole integer (like a dice roll from 1 to 6).
To get a random integer, you must combine Math.random() with Math.floor() (to round down to a whole number) and multiplication (to scale the number up).
If we multiply Math.random() by 10, the result will be a decimal between 0 and 9.999...
If we then apply Math.floor() to that result, the decimal part is chopped off, leaving us with an integer between 0 and 9!
// Math.random() returns a number between 0 and 0.999... // Multiplying by 10 makes it between 0 and 9.999... // Math.floor() rounds it down to 0, 1, 2... up to 9!let randomInt = Math.floor(Math.random() * 10); console.log(randomInt);
Because Math.floor(Math.random() * 10) generates a number from 0 to 9, if we want a number from 1 to 10, we simply add 1 to the final result!
// Add 1 to shift the range from (0-9) to (1-10) let randomInt = Math.floor(Math.random() * 10) + 1; console.log(randomInt);
Instead of writing the Math.floor(Math.random() * ...) formula every time you need a random number, it is highly recommended to create a reusable function.
This function generates a random number between any two numbers (min and max), including the min value and excluding the max value:
// Returns a random integer from min (inclusive) to max (exclusive)
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
console.log(getRndInteger(50, 100)); // Might return 50, but never 100
If you want the maximum number to also be a possible result (inclusive), you just need to add + 1 inside the formula multiplier:
// Returns a random integer from min (inclusive) to max (inclusive)
function getRndIntegerInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
You can copy these two functions and use them safely in all your JavaScript projects!
Which formula is used to generate a random integer between 0 and 5 (inclusive of 0, inclusive of 5)?