The simplest way to create a random number in JavaScript is with Math.random(), which returns a decimal between 0 (inclusive) and 1 (exclusive). To get a random integer in a range, combine it with Math.floor(), for example Math.floor(Math.random() * 10) gives a whole number from 0 to 9.
How Math.random() Works Under the Hood
Math.random() is a built-in function that produces a pseudo‑random floating‑point number in the range [0, 1). That means the smallest possible value is 0 (included) and the largest is just below 1 (never exactly 1). The number has roughly 53 bits of randomness, similar to the precision of a JavaScript double.
It is called “pseudo‑random” because the sequence is generated by a deterministic algorithm. The engine (V8 in Chrome, SpiderMonkey in Firefox, JavaScriptCore in Safari) seeds the generator with some source of entropy, like system time or hardware noise. After seeding, the sequence is reproducible if you knew the seed, but in normal use it appears random enough for games, shuffles, and simple simulations.
One common misconception is that Math.random() is cryptographically secure. It is not. For anything involving security (tokens, passwords, encryption), use the Web Crypto API instead.
Generating Random Integers in a Range
To get a random integer between min (inclusive) 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;
}
For example, getRandomInt(1, 6) simulates a six‑sided die, returning 1, 2, 3, 4, 5, or 6. The +1 inside the multiplication makes the upper bound inclusive. If you want a range that excludes the max, drop the +1.
If you need a random floating‑point number between two values (not just integers), use:
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
This gives a value greater than or equal to min and less than max.
Choosing the Right Approach for Your Use Case
Different situations call for different random generators:
- Simple games or UI effects –
Math.random()is fast and easy. - Statistical sampling or Monte Carlo simulations –
Math.random()is usually fine, but for reproducibility you might want a seeded PRNG (like mulberry32). - Security‑sensitive tasks (password reset tokens, CSRF tokens) – use
crypto.getRandomValues()orcrypto.randomUUID()in modern browsers. - Node.js server‑side – you can use the
cryptomodule’srandomBytes()for secure randomness.
For most everyday coding, Math.random() is perfectly adequate. Just don’t use it for anything that a malicious user could exploit.
Common Pitfalls and Mistakes
One frequent bug is forgetting that Math.random() never returns 1. If you write Math.floor(Math.random() * 10), you get 0–9, not 1–10. To get 1–10, add 1: Math.floor(Math.random() * 10) + 1.
Another issue is using Math.round() instead of Math.floor(). Math.round() skews the distribution because the edge values (0 and max) have half the probability of the middle values. Always use Math.floor() for uniform integer ranges.
Also, be careful with floating‑point precision when the range is very large. For example, Math.floor(Math.random() * 1000000000000) can produce slightly uneven distributions because not every integer is exactly representable. For most purposes this is negligible, but for high‑precision needs, consider using BigInt with a rejection sampling method.
Secure Random Numbers: crypto.getRandomValues()
When you need cryptographically secure randomness, use the Web Crypto API. In browsers, it is available as crypto.getRandomValues(). It fills a typed array with random bytes. For example, to get a secure random integer between 0 and 255:
const array = new Uint8Array(1);
crypto.getRandomValues(array);
const randomByte = array[0]; // 0-255
To get a secure random integer in a range, you can use rejection sampling to avoid modulo bias:
function secureRandomInt(min, max) {
const range = max - min + 1;
const maxAllowed = Math.floor(0xFFFFFFFF / range) * range - 1;
const buffer = new Uint32Array(1);
do {
crypto.getRandomValues(buffer);
} while (buffer[0] > maxAllowed);
return (buffer[0] % range) + min;
}
In Node.js, you can use require('crypto').randomBytes() or the crypto.randomInt() function (available since Node 14.10.0) which is simpler:
const crypto = require('crypto');
const randomInt = crypto.randomInt(1, 7); // 1-6
Shuffling an Array Randomly
A common need is to shuffle an array. The Fisher–Yates shuffle is the correct algorithm. A simple implementation:
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 iterates from the end, picking a random index from 0 to i, and swaps. It runs in O(n) time and produces a uniform distribution. Avoid the naive array.sort(() => Math.random() - 0.5) because it is biased and slower.
Seeded Random Number Generators
Sometimes you want the same sequence of random numbers every time, for testing or procedural generation. JavaScript does not provide a built‑in seedable PRNG, but you can implement a simple one. One popular choice is 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(42);
console.log(rand()); // 0.26407236791215837
This returns a function that produces a float in [0,1) based on the seed. You can then use it in place of Math.random(). For more robust needs, consider libraries like seedrandom or random-js.
Frequently Asked Questions
How do I get a random number between 1 and 10 in JavaScript?
Use Math.floor(Math.random() * 10) + 1. This gives an integer from 1 to 10 inclusive. The * 10 scales the random decimal to 0–9.999, Math.floor truncates to 0–9, and +1 shifts it to 1–10.
Why does Math.random() sometimes return 0 but never 1?
By specification, Math.random() returns a number greater than or equal to 0 and less than 1. The upper bound is exclusive, so 1 is never returned. This is intentional and makes it easy to create ranges with Math.floor().
Is Math.random() safe for passwords or tokens?
No. Math.random() is not cryptographically secure; its output can be predicted if the seed is known. For any security‑sensitive data, use crypto.getRandomValues() in browsers or crypto.randomInt() in Node.js.
How can I make a random number generator that repeats the same sequence?
Use a seeded PRNG like the mulberry32 function shown above. You provide a seed value, and the generator will produce the same sequence every time you start with that seed. This is useful for reproducible random levels or tests.
What is the difference between Math.floor() and Math.round() when generating random integers?
Math.floor() truncates downward, giving a uniform distribution when combined with Math.random(). Math.round() rounds to the nearest integer, which makes the first and last values half as likely as the middle ones, creating bias. Always use Math.floor().
Can I use Math.random() to pick a random element from an array?
Yes: array[Math.floor(Math.random() * array.length)]. This picks a random index from 0 to length-1. For a more secure or unbiased pick, use the secure random integer method described earlier.
Related
- Data Entry Bir 7.4? Meaning & How to Use It
- Shortcut for AutoSum in Excel (Windows & Mac)
- What Does Data Entry Consist Of?
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Date Drop-Down Lists: Setup, Limits, and FixesIn Excel for Microsoft 365 on Windows, create a date drop-down by putting the permitted dates in a…
- Excel Custom Number Format: Hide Zeros Without Deleting ThemYes. In Excel for Microsoft 365 on Windows, apply a custom number format such as 0;-0;;@ to show…
- Edit a Data Validation List in Excel: Steps and FixesTo edit a data validation list in Microsoft Excel for Microsoft 365 on Windows, select a cell that…
- Google Sheets Daily Schedule Template: Build Your OwnA Google Sheets daily schedule template is a reusable spreadsheet for organizing the day by time, activity, priority,…
- How to Split a String Into an Array in JavaScriptUse JavaScript’s String.prototype.split() method to turn a string into an array: for example, 'red,green,blue'.split(',') returns ['red', 'green', 'blue'].…
- Excel Zoom Shortcut: How to Zoom In, Out, and Set ScaleIn Excel for Microsoft 365 on Windows, press Alt+W, Q to open the Zoom dialog, enter a percentage…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.