JavaScript Random Number Generator
Random numbers in JavaScript: a random integer in any range, floats, picking and shuffling, and secure random values - with ready-to-paste code
How to generate a random number in JavaScript: Math.random() for UI and games, the Web Crypto API for anything security-related. Choose a range above for a ready-to-paste function.
Random Integer Between Min and Max
Math.random() returns a float in [0, 1). Multiply by the number of possible values, floor it, and add the minimum.
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min; // min..max inclusive
}
randomInt(1, 10);
Random Float
Scale Math.random() to any range of decimals.
Math.random(); // 0 <= x < 1
const x = Math.random() * (5 - 1.5) + 1.5; // 1.5 <= x < 5
Random Array Element and Shuffle
Pick an index at random, or shuffle with Fisher-Yates - sorting with () => Math.random() - 0.5 gives a biased order.
const items = ["red", "green", "blue", "yellow"];
const pick = items[Math.floor(Math.random() * items.length)];
// Fisher-Yates shuffle (in place)
for (let i = items.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[items[i], items[j]] = [items[j], items[i]];
}
Secure Random Numbers
Math.random() is not cryptographically secure. For tokens, IDs and draws use the Web Crypto API (browsers and Node 19+), or crypto.randomInt in Node.
const bytes = crypto.getRandomValues(new Uint8Array(16)); // 16 random bytes
const id = crypto.randomUUID(); // random UUID v4
// Node.js
const { randomInt } = require("node:crypto");
randomInt(1, 11); // 1..10 (upper bound exclusive)
Common Mistakes
Math.round(Math.random() * 10) makes 0 and 10 half as likely as the other values; Math.floor(Math.random() * 10) never returns 10. Use the floor formula with max - min + 1.
Frequently Asked Questions
How do I generate a random number between 1 and 10 in JavaScript? ▶
Is Math.random() secure? ▶
How do I get a random element from an array? ▶
How do I shuffle an array in JavaScript? ▶
[ HOW TO CITE THIS PAGE ]
Generate-Random.org. (2026). JavaScript Random Number Generator. Retrieved from https://generate-random.org/random-number-javascript
JavaScript Random Number Generator - Generate-Random.org (https://generate-random.org/random-number-javascript)