Math.random() returns a pseudo-random JavaScript number from 0 inclusive up to 1 exclusive. Scale and round that value to create ranges.
const value = Math.random();
console.log(value); // 0 <= value < 1Math.random()The method takes no arguments. It can return 0, but it does not return 1.
function randomBetween(min, max) {
return Math.random() * (max - min) + min;
}
console.log(randomBetween(5, 10)); // 5 <= value < 10function randomInt(min, max) {
const minCeiled = Math.ceil(min);
const maxFloored = Math.floor(max);
return Math.floor(Math.random() * (maxFloored - minCeiled) + minCeiled);
}
console.log(randomInt(1, 11)); // 1 through 10function randomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}const value = Math.floor(Math.random() * 10) + 1;
console.log(value);const value = Math.floor(Math.random() * (100 - 90 + 1)) + 90;
console.log(value);These formulas use Math.floor() and sometimes Math.ceil(). Avoid using Math.round() for uniform integer ranges because the edge values receive different-sized intervals.
const colors = ["red", "green", "blue"];
const index = Math.floor(Math.random() * colors.length);
console.log(colors[index]);Math.random() is suitable for ordinary UI examples, games, sampling, and non-security-sensitive choices. Do not use it to generate passwords, reset tokens, session identifiers, cryptographic keys, or other secrets. Browser code should use crypto.getRandomValues() for cryptographically strong random values.
A common mistake is to shuffle an array with array.sort(() => Math.random() - 0.5). That does not produce an unbiased shuffle. When fair random ordering matters, use a proper algorithm such as Fisher-Yates.
function shuffle(items) {
const copy = [...items];
for (let i = copy.length - 1; i > 0; i -= 1) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}Random output makes automated tests harder to reproduce. Put the random-number generation behind a small function or inject a generator when deterministic tests are important. This separates the application logic from the source of randomness.
Try the random-number generator demo. Related versions are available for PHP and ASP.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.