JavaScript Random
JavaScript's Math.random()
generates a pseudo-random number between 0 (inclusive) and 1 (exclusive). By manipulating this value, you can generate random integers or select random items from arrays.
Key Topics
Basic Random
Math.random()
returns a floating-point number from 0 up to but not including 1.
let randomNum = Math.random();
console.log(randomNum);
Output
> A number like 0.123456789 (varies each run)
Explanation: The exact output varies, but it will always be between 0 and 1.
Random in a Range
You can multiply and floor the result to get integers within a specific range.
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
console.log(getRandomInt(10));
Output
> An integer between 0 and 9
Explanation: Multiplying by max
and flooring truncates to a whole number within [0, max-1].
JavaScript Usage in DOM
This example shows how to generate a random number and display it on the webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random in DOM</title>
</head>
<body>
<h1>Random Number Demo</h1>
<button onclick="showRandom()">Show Random Number</button>
<p id="display"></p>
<script>
function showRandom() {
let num = Math.floor(Math.random() * 100);
document.getElementById("display").textContent = "Random: " + num;
}
</script>
</body>
</html>
Key Takeaways
- Math.random(): Generates a number in [0,1).
- Scaling and Flooring: Multiply and use
Math.floor()
for integer ranges. - DOM Integration: Display random results interactively on webpages.