To generate a random number between a range in JavaScript, use Math.random() combined with Math.floor(): for a random integer between min (inclusive) and max (inclusive), the formula is Math.floor(Math.random() * (max - min + 1)) + min. For a random decimal (float) between min (inclusive) and max (exclusive), use Math.random() * (max - min) + min.
How Math.random() Works Under the Hood
Math.random() is a built-in JavaScript function that returns a pseudo-random floating-point number in the range [0, 1) — meaning it can return 0 but never exactly 1. The value is generated using an algorithm (typically a linear congruential generator or a more modern PRNG like xorshift, depending on the engine) that produces a sequence of numbers that appear random but are deterministic based on an internal seed.
Because the range is [0, 1), multiplying by a span and adding a base shifts and scales the output. For example, Math.random() * 10 gives values from 0 up to (but not including) 10. Adding 5 gives values from 5 up to (but not including) 15. To get an integer, you use Math.floor() to round down to the nearest whole number, which is crucial because Math.round() would bias the distribution.
Generating Random Integers (Inclusive Range)
The most common need is a random integer between two endpoints, both inclusive. The formula is:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Why +1? Because Math.random() never returns 1, so without the +1, the maximum value would be max - 1. For example, getRandomInt(1, 6) simulates a six-sided die. The multiplication (6 - 1 + 1) = 6 gives a value from 0 to 5.999…, Math.floor gives 0 to 5, and adding 1 gives 1 to 6. Each outcome has an equal probability (uniform distribution).
If you need a range starting at 0, you can simplify: Math.floor(Math.random() * (max + 1)) gives an integer from 0 to max inclusive.
Generating Random Floats (Decimals)
For a random decimal between min (inclusive) and max (exclusive), use:
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
This returns a value like 3.141592653589793. If you need to round it to a specific number of decimal places, use toFixed() or Math.round(). For example, to get a float between 0 and 1 with two decimals:
const randomTwoDecimals = Math.round((Math.random() * 100)) / 100;
Note that toFixed() returns a string, so you’ll need to convert it back with Number() if you need a number.
Common Mistakes and How to Avoid Them
- Using Math.round() instead of Math.floor():
Math.round()biases the distribution because it rounds up when the fractional part is ≥ 0.5, making the endpoints half as likely. Always useMath.floor()for uniform integer distribution. - Forgetting the +1 for inclusive max: Without it, your max value is never returned. Test with
getRandomInt(1, 2)— you should get 1 or 2 equally, but without +1 you’d only get 1. - Swapping min and max: The formula assumes
max > min. If you pass them in the wrong order, you’ll get unexpected results. Add a check likeif (min > max) [min, max] = [max, min]if needed. - Using Math.random() for security: It is not cryptographically secure. For passwords, tokens, or any security-sensitive use, use
crypto.getRandomValues()(see below).
Cryptographically Secure Random Numbers
If you need random numbers for security purposes (e.g., generating a reset token), Math.random() is not suitable because its output is predictable. Use the Web Crypto API:
function getSecureRandomInt(min, max) {
const range = max - min + 1;
const maxUint32 = 0xFFFFFFFF;
const limit = maxUint32 - (maxUint32 % range);
let x;
do {
x = crypto.getRandomValues(new Uint32Array(1))[0];
} while (x >= limit);
return (x % range) + min;
}
This uses rejection sampling to avoid modulo bias. In Node.js, use crypto.randomInt(min, max) for integers (available in Node 14.10+).
Alternative Approaches: Libraries and Built-ins
While the manual formula is simple, some libraries offer convenience. For example, Lodash has _.random(min, max, true) for floats. However, for most projects, the native method is sufficient and avoids dependencies.
In modern JavaScript, there’s no built-in function for random integers in a range, but you can use Math.random() as shown. Some developers use Math.floor(Math.random() * (max - min + 1)) + min so often that they create a utility function. For Node.js, the crypto module provides randomInt() which is more secure and easier to use:
const { randomInt } = require('crypto');
const num = randomInt(1, 7); // 1 to 6 inclusive
Performance and Precision Considerations
Math.random() is fast — typically a few nanoseconds per call. But if you generate millions of random numbers in a tight loop, the PRNG’s quality matters. V8 (Chrome/Node) uses xorshift128+, which is adequate for most uses. For simulations or games, it’s fine.
Precision: Math.random() returns a double-precision float, so you have about 53 bits of randomness. For most ranges, that’s more than enough. But if you need a random integer larger than 2^53, you’ll need to combine multiple calls or use a BigInt approach.
Frequently Asked Questions
How do I generate a random number between 1 and 10 in JavaScript?
Use Math.floor(Math.random() * 10) + 1. This gives integers from 1 to 10 inclusive. The *10 gives 0 to 9.999…, floor gives 0 to 9, and +1 gives 1 to 10.
Why does Math.random() never return 1?
By specification, it returns a number in the range [0, 1) — that is, greater than or equal to 0 and less than 1. This design makes it easier to scale to any range without special-casing the upper bound.
Is Math.random() truly random?
No, it’s pseudo-random. The sequence is deterministic and can be predicted if the seed is known. For non-security uses like games or sampling, it’s fine. For security, use crypto.getRandomValues().
How do I generate a random boolean?
Use Math.random() < 0.5. This returns true about 50% of the time. For a weighted boolean, adjust the threshold, e.g., Math.random() < 0.8 gives true 80% of the time.
Can I generate a random number in a range without Math.floor?
Yes, if you want a float, you don't need floor. For an integer, you must round down, otherwise you'll get decimals. Alternatively, you can use Math.trunc() but it behaves the same as Math.floor() for positive numbers.
What is the difference between Math.floor and Math.round for random numbers?Math.round() rounds to the nearest integer, which skews the distribution because the endpoints get half the probability. Math.floor() always rounds down, giving each integer an equal chance when used with the correct formula.
Related
- Remove Table Column Formatting in Excel: 3 Ways
- Generate 6 Digit Random Number in Java
- Sign Out Shortcut Windows: 5 Fast Ways
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Microsoft Access vs Excel: Which Tool Fits Your Work?Use Microsoft Access when you need a structured database to manage related records, prevent inconsistent data, and build…
- Mirror Image Flip in Excel: What Works and HowTo mirror a picture in Excel for Microsoft 365 on Windows, select it and choose Picture Format >…
- COUNTA Excel vs COUNT: Which Cells Do They Count in a Range?In Excel, COUNT counts numbers in a range, while COUNTA counts cells that contain something, including text, numbers,…
- Excel AutoSave: How to Turn It Off and Keep Changes SafeTo turn off AutoSave for the workbook you have open in Excel for Microsoft 365 on Windows, switch…
- Google Sheets Budget Template: Build a Monthly PlanA Google Sheets budget template is a spreadsheet for listing income, planned expenses, and actual spending in one…
- Freeze Cells in Excel While Scrolling: A Step-by-Step GuideTo keep headings visible while you scroll in Excel, select the cell below the rows and to the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.