The simplest JavaScript to generate a random number is Math.random(), which returns a decimal between 0 (inclusive) and 1 (exclusive). For a random integer in a specific range, use Math.floor(Math.random() * (max - min + 1)) + min — for example, Math.floor(Math.random() * 10) + 1 gives a whole number from 1 to 10.
How Math.random() Works Under the Hood
Math.random() is a built-in JavaScript function that produces a pseudo-random floating-point number in the range [0, 1). That means it can return 0 but never 1. The values are generated by an algorithm inside the JavaScript engine (like V8 in Chrome or SpiderMonkey in Firefox), typically based on a seeded pseudo-random number generator (PRNG). The seed is usually derived from system entropy (e.g., time, mouse movements), so the sequence is not truly random but is unpredictable enough for most non-security uses.
Because it’s pseudo-random, the same seed would produce the same sequence, but in practice the engine reseeds frequently, so you won’t see repeating patterns in normal use. The distribution is approximately uniform — each value in the range has roughly equal probability of appearing.
Generating Random Integers in a Range
To get a random integer between min and max (both inclusive), the standard formula is:
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Why does it work? Math.random() gives a value from 0 to 0.999…, multiplying by (max - min + 1) gives a range from 0 to just under (max - min + 1). Flooring that gives an integer from 0 to (max - min), and adding min shifts it to the desired range. For example, getRandomInt(5, 10) can return 5, 6, 7, 8, 9, or 10 with equal probability.
If you want a random integer but exclude the max (e.g., 0 to 9), simply drop the +1: Math.floor(Math.random() * 10).
Random Decimals and Other Distributions
For a random decimal between two numbers (inclusive of min, exclusive of max), use:
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
This returns values like 3.14159 or 7.9999. If you need a fixed number of decimal places, combine with toFixed(): getRandomFloat(1, 5).toFixed(2) gives a string like “3.14”. Note that toFixed returns a string, so parse it back if you need a number.
For a normal (Gaussian) distribution, you can use the Box-Muller transform, which converts two uniform random values into a normally distributed one. This is useful for simulations or generating test data that clusters around a mean.
Choosing the Right Method for Your Use Case
The method you pick depends on what you need:
- Simple random decimal — use
Math.random()directly. - Random integer in a range — use the floor formula above.
- Random element from an array — use
array[Math.floor(Math.random() * array.length)]. - Cryptographically secure random — use
crypto.getRandomValues()(see below). - Seeded random (reproducible) — implement a custom PRNG like mulberry32 or use a library.
For most everyday tasks like picking a random color, shuffling a deck, or generating a test ID, Math.random() is perfectly fine. But if you’re building a lottery, a gambling app, or any security-sensitive feature, you must use a cryptographically secure source.
Common Pitfalls and Misconceptions
One frequent mistake is using Math.round() instead of Math.floor() when generating integers. For example, Math.round(Math.random() * 10) gives numbers from 0 to 10, but 0 and 10 each have half the probability of the other numbers (because rounding boundaries are uneven). This creates bias. Always use Math.floor() for uniform integers.
Another misconception is that Math.random() is truly random. It’s not — it’s deterministic once seeded. For most non-security purposes this is irrelevant, but for cryptography you need a different approach.
Also, be careful with floating-point precision. Multiplying a large range can produce values that are not perfectly uniform due to rounding, but for ranges under 2^53 (about 9 quadrillion), the bias is negligible.
Cryptographically Secure Random Numbers
For security-sensitive applications (passwords, tokens, encryption keys), use the Web Crypto API:
function secureRandomInt(max) {
const range = max;
const maxUint = 4294967295; // 2^32 - 1
const randomBuffer = new Uint32Array(1);
crypto.getRandomValues(randomBuffer);
return randomBuffer[0] % range;
}
This uses the browser’s cryptographic random generator, which is seeded from system entropy and is designed to be unpredictable. Note that modulo bias can occur if max does not evenly divide 2^32; for strict uniformity, use rejection sampling. In Node.js, you can use crypto.randomInt() (available since Node 14.10) which handles this correctly:
const crypto = require('crypto');
const randomInt = crypto.randomInt(1, 11); // integer from 1 to 10
Never use Math.random() for anything related to security — it is not designed for that and can be predicted if the seed is known.
Seeded Random Number Generators
Sometimes you need a reproducible sequence — for example, in a game level generation or a test suite. Math.random() cannot be seeded directly in standard JavaScript. Instead, implement a small PRNG like mulberry32:
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;
};
}
const rand = mulberry32(12345);
console.log(rand()); // always 0.7522... for seed 12345
This returns a function that produces uniform decimals in [0,1) and is deterministic for a given seed. You can then use the same floor formula to get integers. Libraries like seedrandom also provide this functionality.
Frequently Asked Questions
How do I generate a random number between 1 and 100?
Use Math.floor(Math.random() * 100) + 1. This gives an integer from 1 to 100 inclusive. The +1 shifts the range from 0-99 to 1-100.
Why is Math.random() not secure?
Because it’s a pseudo-random generator with a seed that may be predictable. If an attacker can determine the seed or observe enough outputs, they can predict future values. For security, use crypto.getRandomValues() in browsers or crypto.randomInt() in Node.js.
Can I get a random number without Math.random()?
Yes, you can use crypto.getRandomValues() for secure randomness, or implement your own PRNG with a seed. For example, a simple LCG (linear congruential generator) can produce random-looking numbers, but it’s not cryptographically secure.
How do I generate a random number in Node.js?
In Node.js, Math.random() works the same as in browsers. For secure random integers, use crypto.randomInt(min, max) from the built-in crypto module. For example, crypto.randomInt(1, 7) gives a number from 1 to 6.
What is the difference between Math.floor and Math.round for random integers?
Math.floor() truncates downward, giving a uniform distribution when used with Math.random(). Math.round() rounds to the nearest integer, which makes the first and last numbers in the range half as likely as the middle ones, creating bias.
Can I generate a random boolean?
Yes, use Math.random() < 0.5 to get true or false with equal probability. For a weighted boolean, change the threshold, e.g., Math.random() < 0.8 gives true 80% of the time.
Related
- Google Sheets Query Not Equal: Syntax & Examples
- Google Sheets Query Named Columns: How To
- Random 4 Digit Code: How to Generate One
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Google Sheets IF Blank: Formulas, Examples, and FixesIn Google Sheets, use =IF(A2="","Blank","Not blank") to test whether A2 is empty or returns an empty string; replace…
- Oracle String to Number: TO_NUMBER and Casting GuideThe primary Oracle function to convert a string to a number is TO_NUMBER, used as TO_NUMBER('123.45'). You can…
- How to Apply Styles in a Word Document for Clear FormattingTo apply a style in Microsoft Word, click in a paragraph or select text, then choose a style…
- Excel Custom Number Format Color Codes and ExamplesIn an Excel custom number format, add a color name in square brackets at the start of a…
- Create an Email Distribution List in Outlook 365To create an email distribution list in Outlook 365, open People and choose New contact list in new…
- Enter Serial Numbers in Excel: Manual and Automatic MethodsTo create a numbered list in Excel, enter 1 and 2 in the first two cells, select both,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.