To generate a random number in JavaScript, use Math.random(), which returns a floating-point number between 0 (inclusive) and 1 (exclusive). For a random integer in a specific range, combine it with Math.floor(), as in Math.floor(Math.random() * max) for 0 up to (but not including) max.
How Math.random() Works Under the Hood
Math.random() is a built-in JavaScript function that produces a pseudo-random number. “Pseudo” means the numbers are generated by an algorithm, not by a truly random physical process. The algorithm used varies by JavaScript engine (V8 in Chrome, SpiderMonkey in Firefox, JavaScriptCore in Safari), but the result is always a double-precision floating-point number in the range [0, 1). That means 0 can be returned, but 1 never is. The function is seeded internally, typically with a value derived from the system time or other entropy sources, so each page load produces a different sequence.
Because Math.random() is not cryptographically secure, it should never be used for anything involving security, such as generating passwords, tokens, or lottery numbers. For those use cases, use the Web Crypto API’s crypto.getRandomValues() instead.
Generating Random Integers in a Range
The most common task is getting a random integer between two values, say min and max (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;
}
This works by scaling the random fraction to the width of the range, then shifting it up by min. For example, getRandomInt(1, 10) returns a whole number from 1 to 10 inclusive. If you want an exclusive max (like a dice roll that never shows 7 on a d6), use Math.floor(Math.random() * (max - min)) + min.
Here is a quick reference for common ranges:
- Random integer 0 to 9:
Math.floor(Math.random() * 10) - Random integer 1 to 100:
Math.floor(Math.random() * 100) + 1 - Random integer 5 to 15 inclusive:
Math.floor(Math.random() * 11) + 5
Choosing the Right Method for Your Use Case
Not all random number needs are the same. Here’s how to decide:
- Simple games, UI effects, or non-critical randomness –
Math.random()is fine and fast. - Cryptographic purposes (passwords, tokens, encryption) – Use
crypto.getRandomValues()orcrypto.randomUUID()for UUIDs. - Statistical simulations requiring reproducibility – Use a seeded pseudo-random number generator (PRNG) like mulberry32 or a library such as seedrandom.
If you need a random element from an array, you can do:
const items = ['apple', 'banana', 'cherry'];
const randomItem = items[Math.floor(Math.random() * items.length)];
Common Pitfalls and How to Avoid Them
One frequent mistake is using Math.round() instead of Math.floor(). Math.round() creates a biased distribution because the edges (0 and max) get half the probability of the middle values. For example, Math.round(Math.random() * 10) gives 0 and 10 each about half as often as 1 through 9. Always use Math.floor() for uniform integer ranges.
Another pitfall is forgetting that Math.random() never returns 1, so if you write Math.floor(Math.random() * 10) + 1 to get 1–10, you actually get 1–10 correctly, but if you write Math.ceil(Math.random() * 10) you get 1–10 but with a tiny chance of 0 (when the random number is exactly 0). That is why Math.floor() is preferred.
Also, be careful when using Math.random() in a loop that runs very quickly. Since the seed is based on time, two calls in the same millisecond could theoretically produce correlated values, but in practice modern engines handle this well. For most applications this is a non-issue.
Cryptographically Secure Random Numbers
When you need randomness that cannot be predicted, use the Web Crypto API. It is available in all modern browsers and in Node.js (via the crypto module). Here’s an example that returns a random integer between 0 and 255:
function getSecureRandomByte() {
const array = new Uint8Array(1);
crypto.getRandomValues(array);
return array[0];
}
For a random integer in a range, you can use rejection sampling to avoid bias:
function secureRandomInt(min, max) {
const range = max - min + 1;
const maxValid = Math.floor(0x100000000 / range) * range;
const buffer = new Uint32Array(1);
do {
crypto.getRandomValues(buffer);
} while (buffer[0] >= maxValid);
return min + (buffer[0] % range);
}
This ensures each number in the range has equal probability. For generating a UUID, use crypto.randomUUID() which is supported in modern browsers.
Real-World Examples and Code Snippets
Here are a few practical implementations:
Roll a six-sided die:
const dieRoll = Math.floor(Math.random() * 6) + 1; // 1 to 6
Pick a random card from a deck (assuming an array of card objects):
const deck = [{suit:'hearts', rank:'A'}, /* ... */];
const randomCard = deck[Math.floor(Math.random() * deck.length)];
Shuffle an array (Fisher-Yates):
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
This shuffle is unbiased, meaning every permutation is equally likely.
Performance and Precision Considerations
Math.random() is extremely fast—millions of calls per second are typical. It is also precise enough for most applications, giving about 53 bits of randomness (since it uses a double). If you need more precision or a specific distribution (like Gaussian), you’ll need to implement or use a library.
For simulations that require reproducibility (e.g., testing), you can use a seeded PRNG. Here’s a simple mulberry32 implementation:
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(42);
rand(); // always the same sequence for seed 42
Frequently Asked Questions
Why does Math.random() sometimes return 0 but never 1? The specification says it returns a number in the interval [0, 1), meaning 0 is possible and 1 is not. This is to make it easier to scale to integer ranges without off-by-one errors.
Can I use Math.random() for a password generator? No. Math.random() is not cryptographically secure; an attacker could predict the sequence. Use crypto.getRandomValues() or a dedicated library like uuid for security-sensitive randomness.
How do I get a random number between two floats, like 1.5 and 3.5? Use Math.random() * (max - min) + min. For example, Math.random() * 2 + 1.5 gives a float from 1.5 to 3.5 (exclusive of 3.5).
Is there a way to make Math.random() truly random? No, it is pseudo-random. For true randomness, you would need hardware entropy, which the Web Crypto API uses under the hood. But for most non-security purposes, pseudo-random is sufficient.
Why is using Math.round() with Math.random() bad? Because it creates a non-uniform distribution: the minimum and maximum values have half the probability of the middle values. This can skew results in games or simulations.
Can I generate a random number in a range without using Math.floor()? You could use bitwise operators like ~~ or | 0 to truncate, but they only work for 32-bit integers and can behave unexpectedly with large numbers. Math.floor() is clearer and safer.
Related
- Forecast Sheet in Excel: How to Use It
- Google Sheets Query Group By Multiple Columns
- Public Data Entry Registration: How It Works
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Power Query to Combine Excel Files: A Practical GuideTo combine multiple Excel files in Microsoft 365 for Windows, put them in one folder, then select Data…
- Excel Remove Duplicates in One Column Without Losing DataTo remove duplicate values from a column in Excel for Microsoft 365 on Windows, select the column or…
- Excel Mac Conditional Formatting: Rules and FixesIn Excel for Mac, select the cells you want to format, then choose Home > Conditional Formatting and…
- How to Add Subtotals in Google SheetsAdding subtotals in Google Sheets lets you automatically group and sum data by category, such as total sales…
- How to Import an Excel Sheet Into Word: 3 Simple MethodsTo import Excel content into Word, select and copy the cells in Excel, then paste them into your…
- Excel Borders: How to Add, Change, and Remove Cell LinesTo add a border in an Excel spreadsheet, select the cell or range, then choose Home > Borders…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.