What is JavaScript Random Method?
The Math.random() method in JavaScript generates a random decimal number between 0 (inclusive) and 1 (exclusive). While this method is simple, it is a foundational tool for many real-world applications, such as gaming logic, data simulations, password generators and more.
How Math.random() Works
The Math.random() method generates a pseudo-random number. This means the number is not truly random but is generated using an algorithm that mimics randomness. Despite this limitation, the results are sufficient for most general purposes.
Example:
console.log(Math.random()); // Output: A random number between 0 and 1, like 0.435678123
Generating Custom Random Numbers
1. Random Integer Between Two Values
To generate a random integer between a minimum (min) and maximum (max) value (inclusive):
Formula:
Math.floor(Math.random() * (max - min + 1)) + min;
Example:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(1, 10)); // Output: Random integer between 1 and 10
2. Random Float Between Two Values
To generate a random floating-point number between two values:
Formula:
Math.random() * (max - min) + min;
Example:
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
console.log(getRandomFloat(1.5, 5.5)); // Output: Random float between 1.5 and 5.5
3. Random Boolean
A random boolean can be created by checking whether a random number is greater or less than 0.5:
Example:
function getRandomBoolean() {
return Math.random() >= 0.5;
}
console.log(getRandomBoolean()); // Output: true or false
Applications of Math.random()
1. Simulating a Dice Roll
Simulating the roll of a dice involves generating a random number between 1 and 6:
Example:
function rollDice() {
return Math.floor(Math.random() * 6) + 1;
}
console.log(rollDice()); // Output: Random integer between 1 and 6
2. Flipping a Coin
A coin flip returns either “Heads” or “Tails” based on a random boolean:
Example:
function flipCoin() {
return Math.random() >= 0.5 ? "Heads" : "Tails";
}
console.log(flipCoin()); // Output: Heads or Tails
3. Random Array Element
To pick a random element from an array:
Example:
const colors = ["Red", "Green", "Blue", "Yellow"];
function getRandomElement(arr) {
const index = Math.floor(Math.random() * arr.length);
return arr[index];
}
console.log(getRandomElement(colors)); // Output: Random color from the array
4. Random Hex Color Generator
Generate a random hex color code:
Example:
function getRandomHexColor() {
return `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0")}`;
}
console.log(getRandomHexColor()); // Output: Random hex color like #f3a1b2
5. Shuffling an Array
Randomly shuffle the elements of an array:
Example:
function shuffleArray(arr) {
return arr.sort(() => Math.random() - 0.5);
}
const numbers = [1, 2, 3, 4, 5];
console.log(shuffleArray(numbers)); // Output: Randomly shuffled array
Limitations of Math.random()
- Pseudo-Randomness:
Numbers generated are not truly random and can be predicted in highly secure systems. - Not Suitable for Cryptography:
For sensitive tasks like password generation, use cryptographic functions like the Web Crypto API (window.crypto).
Example:
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
console.log(array[0]); // Output: Cryptographically secure random number
Practical Example: Simple OTP Generator
Generate a 6-digit random OTP (One-Time Password):
Example:
function generateOTP() {
return Math.floor(Math.random() * 900000) + 100000;
}
console.log(generateOTP()); // Output: Random 6-digit number like 394582