In JavaScript, random numbers are generated using the Math.random() method, which returns a floating-point number between 0 (inclusive) and 1 (exclusive). For integers or numbers in a specific range, you combine Math.random() with arithmetic and rounding, and for cryptographically secure randomness you use the Web Crypto API’s crypto.getRandomValues().
How Math.random() Works Under the Hood
Math.random() is a built-in function that produces a pseudo-random number. It uses an algorithm known as a pseudo-random number generator (PRNG), which starts from an internal seed and applies a deterministic mathematical process to generate a sequence that appears random. The exact algorithm is not specified by the ECMAScript standard, so implementations vary by browser and JavaScript engine (e.g., V8 in Chrome uses xorshift128+). The output is a double-precision floating-point number in the range [0, 1).
Because it’s pseudo-random, the sequence is reproducible if the seed is known, but the seed is set automatically and is not accessible to the developer. For most non-security applications, Math.random() is sufficient.
Generating Random Integers in a Range
The most common task is generating a random integer between a minimum and maximum value (inclusive). A typical formula is:
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
For example, getRandomInt(1, 6) simulates a die roll. The Math.ceil and Math.floor ensure the range is inclusive. If you need a random number between 0 and 1 exclusive, just use Math.random() directly.
Why Math.random() Is Not Suitable for Security
Math.random() is not cryptographically secure. The sequence can potentially be predicted if an attacker knows the algorithm and seed, or if they observe enough outputs. For anything involving passwords, tokens, encryption keys, or gambling, you must use the Web Crypto API.
The Web Crypto API provides crypto.getRandomValues(), which fills a typed array with cryptographically secure random values. Example:
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
console.log(array[0]); // a random 32-bit unsigned integer
To get a random integer in a range securely, you can use rejection sampling to avoid modulo bias:
function secureRandomInt(min, max) {
const range = max - min + 1;
const maxUint = 0xFFFFFFFF;
const limit = maxUint - (maxUint % range);
let x;
do {
const buf = new Uint32Array(1);
crypto.getRandomValues(buf);
x = buf[0];
} while (x >= limit);
return min + (x % range);
}
This ensures each value in the range has an equal probability.
Common Pitfalls and Misconceptions
One common mistake is using Math.round() instead of Math.floor() when scaling. For example, Math.round(Math.random() * 5) gives values 0 to 5 but with a bias: 0 and 5 have half the probability of 1–4. Always use Math.floor().
Another misconception is that Math.random() can be seeded. In standard JavaScript, there is no way to set a seed for Math.random(). If you need reproducible sequences (e.g., for testing or procedural generation), implement your own PRNG like a linear congruential generator or use a library.
Implementing a Seedable Random Number Generator
For cases where you need reproducibility, you can write a simple PRNG. A common one is the mulberry32 algorithm:
function mulberry32(seed) {
return function() {
seed |= 0; seed = seed + 0x6D2B79F5 | 0;
let t = Math.imul(seed ^ seed >>> 15, 1 | seed);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
}
// Usage:
const rng = mulberry32(42);
console.log(rng()); // first random number
This returns a function that produces a float in [0,1). You can then scale it like Math.random(). This is useful for games and simulations where you want the same sequence every run.
Performance Considerations
Math.random() is very fast, typically taking nanoseconds per call. crypto.getRandomValues() is slower because it gathers entropy from the system, but still fine for occasional use. If you need many random numbers (e.g., millions), stick with Math.random() unless security is required.
Alternatives and Libraries
For complex needs, libraries like seedrandom provide seedable PRNGs with better statistical quality. For cryptographic randomness in Node.js, you can use crypto.randomBytes() or crypto.randomInt() (Node 14.10+). In the browser, crypto.getRandomValues() is the standard.
Frequently Asked Questions
How do I get a random number between 1 and 10 in JavaScript?
Use Math.floor(Math.random() * 10) + 1. This gives integers from 1 to 10 inclusive.
Is Math.random() truly random?
No, it’s pseudo-random. It is deterministic based on an internal seed, but the seed is set automatically and not accessible. For most purposes it’s fine, but not for security.
Can I set a seed for Math.random()?
No, the standard does not provide a seed option. You’ll need to implement your own PRNG or use a library like seedrandom.
Why is Math.random() not secure?
Because it’s a PRNG with a predictable algorithm. If an attacker can guess the seed or observe enough outputs, they can predict future values. The Web Crypto API uses a CSPRNG (cryptographically secure PRNG) that is designed to be unpredictable.
What is the difference between Math.random() and crypto.getRandomValues()?
Math.random() is fast, non-secure, and returns a float in [0,1). crypto.getRandomValues() is slower, cryptographically secure, and fills a typed array with integers. Use the latter for anything security-related.
How do I generate a random float between two numbers?
Use Math.random() * (max - min) + min. For example, a float between 5 and 10: Math.random() * 5 + 5.
Related
- Data Entry for Registration of Documents: How It Works
- Ctrl+Z Shortcut: What It Does and How to Use It
- Forecast Sheet in Excel: How to Use It
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Add an MLA Header in Word: A Step-by-Step GuideTo add an MLA header in Microsoft Word, right-align the header, type your last name and a space,…
- Google Sheets Join Tables: Methods, Formulas, and TipsYes. Google Sheets can join tables by matching a shared key, usually with XLOOKUP or VLOOKUP for one…
- Insert a Line in Word for the Web: Easy Steps and FixesTo insert a line in Word for the web, choose Insert > Shapes, select a straight line, and…
- Add Slide Numbers to All PowerPoint SlidesTo add slide numbers to every slide in PowerPoint for Microsoft 365 on Windows, go to Insert >…
- Google Sheets Journal Template: Build a Useful Daily LogA Google Sheets journal template is a spreadsheet you set up to record dated entries, moods, habits, or…
- How to Enable Word Wrap in Excel and Adjust Cell TextTo enable word wrap in Excel, select the cell or cells, then choose Home > Wrap Text. Excel…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.