The simplest way to generate a random integer between two values (inclusive of both) in JavaScript is Math.floor(Math.random() * (max - min + 1)) + min. For a random decimal between min (inclusive) and max (exclusive), use Math.random() * (max - min) + min.
How Math.random() Works
Math.random() returns a floating-point number in the range [0, 1) — that is, from 0 (inclusive) up to but not including 1. It uses a pseudo-random number generator (PRNG) that is seeded by the browser or Node.js environment. The output is not cryptographically secure, meaning it should not be used for anything that requires unpredictability, like security tokens or lottery draws.
The core idea is to scale this 0-to-1 value to your desired range. If you want a number from 0 to 9, you multiply by 10 and then use Math.floor() to drop the decimal part, giving integers 0–9. To shift the range to start at a different value, you add the minimum.
Generating a Random Integer (Inclusive)
The most common need is a random integer between two endpoints, including both. The formula is:
Math.floor(Math.random() * (max - min + 1)) + min
Here’s why: Math.random() gives a value from 0 to 0.999…, so Math.random() * (max - min + 1) gives a value from 0 up to but not including max - min + 1. After Math.floor(), you get an integer from 0 to max - min. Adding min shifts it to min through max inclusive.
Example: to get a random integer from 5 to 10 (inclusive):
const randomInt = Math.floor(Math.random() * (10 - 5 + 1)) + 5; // returns 5,6,7,8,9,or 10
Generating a Random Float (Non-Inclusive Max)
For a decimal number between a minimum (inclusive) and a maximum (exclusive), use:
Math.random() * (max - min) + min
This returns a value from min up to but not including max. For example, to get a random float between 1.5 and 3.5 (including 1.5, excluding 3.5):
const randomFloat = Math.random() * (3.5 - 1.5) + 1.5; // e.g., 2.3456
If you need the maximum to be inclusive, you can use (max - min) and then round to a certain number of decimal places, but that’s less common.
Common Mistakes and Gotchas
- Forgetting the +1 in the integer formula – Without
+1, the max value is never included. For example,Math.floor(Math.random() * 10)gives 0–9, not 1–10. - Using
Math.round()instead ofMath.floor()–Math.round()makes the endpoints half as likely as the middle values, so the distribution is not uniform. Always useMath.floor()for integers. - Assuming
Math.random()is cryptographically secure – It is not. For security, usewindow.crypto.getRandomValues()in browsers orcrypto.randomInt()in Node.js. - Not handling negative ranges – The formula works with negative numbers as long as you keep the order correct. For example, min = -5, max = 5 works fine.
How to Choose the Right Method
Decide based on what you need:
- Integer, inclusive both ends – Use
Math.floor(Math.random() * (max - min + 1)) + min. - Float, exclusive max – Use
Math.random() * (max - min) + min. - Float with a specific number of decimal places – Multiply, round, then divide. For example,
Math.round((Math.random() * 100)) / 100gives two decimal places between 0 and 1. - Cryptographically secure random – Use
crypto.getRandomValues()for integers, orcrypto.randomUUID()for unique IDs.
Real-World Examples
Here are a few practical uses:
// Roll a six-sided die
const die = Math.floor(Math.random() * 6) + 1; // 1-6
// Pick a random element from an array
const items = ['apple', 'banana', 'cherry'];
const randomIndex = Math.floor(Math.random() * items.length);
const randomItem = items[randomIndex];
// Generate a random RGB color
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
const color = `rgb(${r},${g},${b})`;
Performance and Alternatives
Math.random() is fast and sufficient for most non-security applications like games, simulations, and random UI effects. For large-scale Monte Carlo simulations, the PRNG quality may matter, but for typical use it’s fine.
If you need a seedable random generator (for reproducible results), consider implementing a simple linear congruential generator (LCG) or using a library like seedrandom. But for basic needs, the built-in is enough.
For secure random numbers, in browsers:
function getRandomIntSecure(min, max) {
const range = max - min + 1;
const bytes = new Uint32Array(1);
window.crypto.getRandomValues(bytes);
return min + (bytes[0] % range);
}
Note that using modulo introduces a slight bias if range does not divide 2^32 evenly, but for most practical ranges it’s negligible. For a perfectly unbiased method, rejection sampling is needed.
Frequently Asked Questions
Why does Math.random() not include 1?
The specification defines Math.random() to return a value in the range [0, 1), meaning 0 is possible but 1 is never returned. This is intentional to make scaling to integer ranges easier without extra edge-case handling.
How do I generate a random number between 1 and 10?
Use Math.floor(Math.random() * 10) + 1. This gives integers from 1 to 10 inclusive. The +1 shifts the range up; the *10 scales the 0-1 value to 0-9.999, and Math.floor makes it an integer.
Is Math.random() good enough for a dice roll in a game?
Yes, for casual games it’s perfectly fine. The distribution is uniform enough for non-competitive use. However, if you’re building an online gambling site or anything where money is involved, you must use a cryptographically secure generator.
Can I generate a random number without Math.random()?
Yes, you can use crypto.getRandomValues() for security, or implement your own PRNG like an LCG if you need seedable randomness. But for most cases, Math.random() is the simplest and fastest.
Why does my random number always come out the same?
That happens if you call the function in a loop but use the same seed or if you’re using a seeded PRNG. With Math.random(), it’s unlikely unless you reset the seed manually (which isn’t possible). If you see the same value repeatedly, check your code for a logic error, like using the same variable without updating it.
Related
- Python Random Numbers: How to Generate Them
- Data Entry Computer Course: What It Covers & Is It Worth It?
- Splitting Strings in Java: Methods and Examples
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Freeze Panes in Excel: Keep Rows and Columns VisibleTo keep headings or labels visible while you scroll in Excel, use View > Freeze Panes. Choose Freeze…
- Excel Trendlines: Which Type Should You Use for Your Data?Use a linear trendline when your data changes at a roughly steady rate; choose another type only when…
- How to Copy in Reverse Order in ExcelTo copy a list in reverse order in Excel, enter an INDEX formula beside the source list, fill…
- Find and Replace Tabs in Excel: Safe MethodsTo replace tab characters inside Excel cells, enter =SUBSTITUTE(A2,CHAR(9)," ") in a helper column, fill it down, then…
- How to Delete Multiple Cells at Once in ExcelTo delete multiple cells at once in Excel, select the cells and press Delete to clear their contents,…
- Revert Text to Columns in Excel: Undo or Rejoin DataTo revert Text to Columns in Excel, press Ctrl+Z immediately after splitting the data; on a Mac, press…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.