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 range, combine it with Math.floor(), like Math.floor(Math.random() * (max - min + 1)) + min.
What Exactly Does Math.random() Return?
Math.random() returns a pseudo-random number in the range [0, 1)—meaning it can be 0 but never exactly 1. The value is a decimal with up to 16 or 17 digits after the decimal point, such as 0.4123456789012345. It is generated by an algorithm inside the JavaScript engine (like V8 in Chrome) and is not cryptographically secure. The distribution is approximately uniform, so each value in the range has an equal chance of appearing.
How to Generate a Random Integer in a Range
The most common task is getting a whole number between a minimum and maximum, 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;
}
Example: getRandomInt(1, 10) returns an integer from 1 to 10, each with equal probability. The +1 ensures the maximum is included; without it, the result would be from min to max-1. If you want a random element from an array, use array[Math.floor(Math.random() * array.length)].
How to Choose a Random Value from an Array
Selecting a random item from an array is straightforward:
const items = ['apple', 'banana', 'cherry'];
const randomIndex = Math.floor(Math.random() * items.length);
const randomItem = items[randomIndex];
This works because Math.random() * items.length gives a value from 0 up to (but not including) the length, and Math.floor converts it to a valid index. For a random property from an object, first get the keys with Object.keys(obj) and then pick a random key.
Common Problems and Misconceptions
- Getting 1 as a result:
Math.random()never returns 1, so if you see 1 in your output, check your formula—you likely usedMath.ceilinstead ofMath.floor. - Inclusive vs. exclusive max: Forgetting the
+1in the integer formula makes the max one less than intended. - Non-uniform distribution: Using
Math.round(Math.random() * (max - min)) + mingives a slightly biased distribution because the endpoints have half the probability. Always useMath.floor. - Security:
Math.random()is not secure. If you need unpredictable values (e.g., for passwords or tokens), usecrypto.getRandomValues()instead.
Cryptographically Secure Random Numbers
For security-sensitive applications, use the Web Crypto API. In modern browsers, crypto.getRandomValues() provides a cryptographically secure random number generator. To get a secure random integer in a range, you can use a rejection sampling technique:
function secureRandomInt(min, max) {
const range = max - min + 1;
const maxUint = 0xFFFFFFFF;
const limit = maxUint - (maxUint % range);
const buf = new Uint32Array(1);
let x;
do {
crypto.getRandomValues(buf);
x = buf[0];
} while (x >= limit);
return min + (x % range);
}
This ensures a uniform distribution without modulo bias. In Node.js, use crypto.randomInt(min, max) for a simpler secure integer.
Random Numbers in Different JavaScript Environments
In browsers, Math.random() is available globally. In Node.js, it also works, but for secure randomness, the crypto module provides randomInt() and randomBytes(). For example, crypto.randomInt(1, 10) returns a secure integer between 1 and 9 (inclusive of 1, exclusive of 10). Note that Math.random() in Node.js is not seeded from a cryptographically secure source, so it is unsuitable for security.
Alternatives and Libraries
If you need more control over the distribution or reproducibility, consider libraries like seedrandom for seeded random numbers (useful for testing), or random-js for a rich API with various distributions. For most simple use cases, Math.random() is sufficient. For scientific simulations, you might need a Gaussian distribution; you can implement the Box-Muller transform, but that is beyond the scope of basic random numbers.
Performance and Best Practices
Math.random() is fast—millions of calls per second are fine. However, avoid generating random numbers inside loops when you can generate a batch once. For example, to shuffle an array, use the Fisher-Yates algorithm:
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 is efficient and unbiased. Remember that Math.random() is deterministic in the sense that it uses a seeded PRNG, but the seed is unpredictable to the user.
Frequently Asked Questions
Why does Math.random() sometimes return 0 but never 1?
By specification, the range is [0, 1). The lower bound is inclusive, so 0 is possible. The upper bound is exclusive, so 1 is never returned. This is to make it easy to map to integers using Math.floor.
Can I seed Math.random() to get reproducible results?
No, the JavaScript specification does not allow seeding Math.random(). Each browser/engine has its own internal seed that is not accessible. For reproducible sequences, use a library like seedrandom or implement your own PRNG.
Is Math.random() safe for generating passwords or tokens?
No. Math.random() is not cryptographically secure; its output can be predicted if an attacker knows the internal state. Always use crypto.getRandomValues() in browsers or crypto.randomBytes() in Node.js for security-sensitive randomness.
How do I get a random float between two numbers, like 5.5 and 8.2?
Use Math.random() * (max - min) + min. For example, Math.random() * (8.2 - 5.5) + 5.5 gives a float between 5.5 (inclusive) and 8.2 (exclusive). If you need the max inclusive, it’s harder; typically you accept the exclusive upper bound.
Why does my random integer sometimes come out as 0 when I use Math.ceil?
Because Math.ceil(Math.random() * 10) can produce 0 if the random value is exactly 0, which is possible. Using Math.floor avoids this because the range starts at 0, and adding a minimum shifts it correctly.
What is the difference between Math.random() and crypto.getRandomValues()?
Math.random() is fast and fine for games, simulations, or any non-security use. crypto.getRandomValues() is slower but cryptographically secure, meaning it is unpredictable to an attacker. Use the latter for anything that affects security or fairness in a competitive context.
Related
- Google Sheets Query Concatenate Columns
- Entry Level Data Entry Companies: Real Jobs & How to Start
- Google Sheets QUERY Concatenate: How to Join Columns
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 Enter a Checkbox in Google Sheets, Step by StepTo enter a checkbox in Google Sheets, select the cell or range where you want it, then choose…
- Excel 3-Color Scale: How It Works and When to Use ItIn Excel for Microsoft 365 on Windows, select the numeric cells, then choose Home > Conditional Formatting >…
- Excel Spreadsheet Grouping Rows: How to Create and Use ItTo group rows in Excel for Microsoft 365 on Windows, select the detail rows, then choose Data >…
- Sample Project Tracker Spreadsheet: Layout and TipsA useful project tracker spreadsheet has one row per task, clear ownership and due dates, a consistent status,…
- How to Add Sound to Slide Transitions in PowerPointTo add a sound to a slide transition in PowerPoint for Microsoft 365 on Windows, select the slide,…
- Cut Shortcut on Mac: The Fastest WaysThe fastest way to cut and paste a file on a Mac is to copy it with Command+C,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.