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(), such as Math.floor(Math.random() * (max - min + 1)) + min.
How Math.random() Works Under the Hood
Math.random() is a built-in JavaScript function that produces a pseudo-random number. It is not truly random—it uses an algorithm (implementation-dependent, often a linear congruential generator or xorshift) seeded by the engine. The output is a decimal with roughly 53 bits of precision, so values like 0.12345678901234567 are possible. The function is deterministic given the same seed, but the seed is set from system entropy at startup, so each page load gives a different sequence.
Because it is pseudo-random, it is fine for games, UI shuffling, and testing. It is not suitable for cryptography, security tokens, or anything where unpredictability matters—use crypto.getRandomValues() for those cases.
Generating a Random Integer in a Specific Range
The most common need is a random whole number between two values. 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 includes both min and max. For example, getRandomInt(1, 10) returns 1, 2, …, 10. If you want to exclude the max, drop the + 1. If you want a floating-point number in a range (e.g., 0.5 to 2.5), use Math.random() * (max - min) + min.
Be careful with negative ranges: the formula works, but ensure min is the lower bound. For instance, getRandomInt(-5, 5) works correctly.
Random Elements from an Array
Picking a random item from an array is a frequent task. Use the integer formula with the array length:
const items = ['apple', 'banana', 'cherry'];
const randomItem = items[Math.floor(Math.random() * items.length)];
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. To shuffle an entire array, the Fisher–Yates algorithm is the standard approach—it iterates backward and swaps each element with a random earlier one.
Common Mistakes and Pitfalls
- Using
Math.round()instead ofMath.floor()– This biases the endpoints. WithMath.round(Math.random() * 10), you get 0 and 10 half as often as 1–9, because the rounding boundaries are uneven. - Forgetting the
+ 1in the range formula – Without it, the max value is never returned. - Assuming
Math.random()can return 1 – It cannot; the upper bound is exclusive. - Using it for passwords or tokens – The sequence is predictable. Attackers can potentially guess values if they know the seed or observe enough outputs.
- Creating a new random number every time you need one – If you need the same random value multiple times (e.g., for a game round), store it in a variable instead of calling
Math.random()repeatedly.
Cryptographically Secure Random Numbers
For security-sensitive applications, use the Web Crypto API. In browsers, crypto.getRandomValues() fills a typed array with cryptographically strong random values. Example:
const array = new Uint32Array(1);
crypto.getRandomValues(array);
const randomNumber = array[0] / 4294967296; // 0 to 1
In Node.js, use crypto.randomInt(min, max) for a secure integer, or crypto.randomBytes() for raw bytes. These are slower but unpredictable. Never use Math.random() for generating API keys, session IDs, or reset tokens.
Randomness in Practice: Games, Shuffles, and Seeds
For game development, Math.random() is usually sufficient. However, if you need a reproducible sequence (e.g., for a seeded world generation), you must implement your own PRNG. A simple mulberry32 algorithm is a common choice:
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(); // deterministic value
This lets you recreate the same sequence by passing the same seed. For shuffling a deck of cards, the Fisher–Yates algorithm with Math.random() gives an unbiased shuffle if implemented correctly.
Alternatives and Libraries
Beyond the built-in functions, several libraries offer more features:
- Chance.js – Provides named generators like
chance.integer({min:1, max:10})and supports seeding. - Seedrandom – A small library that makes
Math.random()seedable, useful for testing and procedural generation. - random-js – A modern library with multiple distributions (normal, exponential, etc.) and pluggable engines.
- Node.js built-in
crypto– For server-side secure randomness without external dependencies.
For most web projects, plain Math.random() is enough. Libraries add convenience but also bundle size, so weigh the trade-off.
Performance and Browser Compatibility
Math.random() is extremely fast—millions of calls per second. It is supported in every JavaScript environment, including all browsers, Node.js, and Deno. The implementation varies by engine, but the API is standardized by ECMAScript. There is no need for polyfills. If you call it in a tight loop (e.g., generating 100,000 random numbers), it will not be a bottleneck. However, crypto.getRandomValues() is slower because it gathers system entropy, so use it sparingly.
Frequently Asked Questions
How do I generate a random number between 1 and 10?
Use Math.floor(Math.random() * 10) + 1. This gives integers 1 through 10, each with equal probability. The + 1 shifts the range from 0–9 to 1–10.
Why does Math.random() sometimes return 0?
It can return 0 because 0 is inclusive in the range [0, 1). The probability is extremely low (about 1 in 2^53), but it is possible. If you need to avoid 0, add a check or use Math.random() || 0.0000000001.
Can I make Math.random() return a negative number?
Yes, by adjusting the formula. For a random integer between -10 and 10, use Math.floor(Math.random() * 21) - 10. The range width is 21 (from -10 to 10 inclusive), and subtracting 10 shifts the start.
Is Math.random() safe for passwords?
No. It is pseudo-random and predictable. Use crypto.getRandomValues() in browsers or crypto.randomBytes() in Node.js for passwords, tokens, or any security-related randomness.
How do I generate a random float between 0 and 100?
Use Math.random() * 100. This gives a decimal from 0 (inclusive) to 100 (exclusive). If you want 100 inclusive, use Math.random() * 101 and then round or floor as needed.
What is the difference between Math.floor and Math.trunc for random numbers?
For positive numbers, they behave the same. For negative numbers, Math.floor(-0.5) gives -1, while Math.trunc(-0.5) gives 0. Since Math.random() only produces non-negative values, you only need Math.floor for the standard range formula.
Related
- VLOOKUP in Google Sheets: How to Use It Correctly
- How to Select All in a Document Folder
- How to Select a Cell and All Cells Below It in Excel
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Porter-Cable PCE201 Impact Driver Review & SpecsThe Porter-Cable PCE201 is a 20V MAX brushed 1/4-inch hex impact driver designed for general-purpose fastening, delivering up…
- Excel Time Tracker: Build One That Adds UpAn Excel time tracker is a spreadsheet for recording when work starts and ends, subtracting breaks, and totaling…
- Make a Flowchart in Word with SmartArt: Steps and LimitsYes. In Word for Microsoft 365, choose Insert > SmartArt, select a Process layout, and enter your steps;…
- Compare Two Excel Sheets and Find Every DifferenceTo compare two Excel sheets, use a cell-by-cell formula when the rows line up, or match records by…
- Google Sheets Filter Just for Me? Use Filter ViewsYes. In Google Sheets, use a filter view to sort or narrow rows for your own view without…
- How to Put a Filter in Google Sheets and Sort DataTo put a filter in Google Sheets, select your data range, including its header row, then choose Data…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.