Discover how to use JavaScript’s Math.random() function to generate random numbers. Learn the syntax, beginner-friendly examples, and real-world use cases like simulating dice rolls and random selection.
Math.random() in JavaScript?Math.random() is a built-in JavaScript method that returns a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). That means it can return 0, but never 1.
Math.random()
0.6543, 0.1234, etc.let num = Math.random();
console.log(num); // e.g., 0.734562
let num = Math.random() * 10;
console.log(num); // e.g., 7.3456
let num = Math.floor(Math.random() * 100) + 1;
console.log(num); // e.g., 84
Simulate rolling a 6-sided dice:
function rollDice() {
return Math.floor(Math.random() * 6) + 1;
}
console.log("You rolled:", rollDice()); // Outputs a number between 1 and 6
Math.random()?