There are some examples on the Mozilla Developer Network page:

/**
 * Returns a random number between min (inclusive) and max (exclusive)
 */
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

/**
 * Returns a random integer between min (inclusive) and max (inclusive).
 * The value is no lower than min (or the next integer greater than min
 * if min isn't an integer) and no greater than max (or the next integer
 * lower than max if max isn't an integer).
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Here's the logic behind it. It's a simple rule of three:

Math.random() returns a Number between 0 (inclusive) and 1 (exclusive). So we have an interval like this:

[0 .................................... 1)

Now, we'd like a number between min (inclusive) and max (exclusive):

[0 .................................... 1)
[min .................................. max)

We can use the Math.random to get the correspondent in the [min, max) interval. But, first we should factor a little bit the problem by subtracting min from the second interval:

[0 .................................... 1)
[min - min ............................ max - min)

This gives:

[0 .................................... 1)
[0 .................................... max - min)

We may now apply Math.random and then calculate the correspondent. Let's choose a random number:

                Math.random()
                    |
[0 .................................... 1)
[0 .................................... max - min)
                    |
                    x (what we need)

So, in order to find x, we would do:

x = Math.random() * (max - min);

Don't forget to add min back, so that we get a number in the [min, max) interval:

x = Math.random() * (max - min) + min;

That was the first function from MDN. The second one, returns an integer between min and max, both inclusive.

Now for getting integers, you could use round, ceil or floor.

You could use Math.round(Math.random() * (max - min)) + min, this however gives a non-even distribution. Both, min and max only have approximately half the chance to roll:

min...min+0.5...min+1...min+1.5   ...    max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘   ← Math.round()
   min          min+1                          max

With max excluded from the interval, it has an even less chance to roll than min.

With Math.floor(Math.random() * (max - min +1)) + min you have a perfectly even distribution.

 min...  min+1...    ...      max-1... max....   (max+1 is excluded from interval)
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘   ← Math.floor()
   min     min+1               max-1    max

You can't use ceil() and -1 in that equation because max now had a slightly less chance to roll, but you can roll the (unwanted) min-1 result too.

Answer from Ionuț G. Stan on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Math › random
Math.random() - JavaScript - MDN Web Docs - Mozilla
The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random ...
🌐
W3Schools
w3schools.com › js › js_random.asp
JavaScript Random
Math.random() returns a number from 0 (inclusive) up to but not including 1.
Discussions

Generating random whole numbers in JavaScript in a specific range - Stack Overflow
I've created a JSFiddle if anyone ... method: jsfiddle.net/F9UTG/1 2013-06-05T13:56:07.693Z+00:00 ... Ionuț G. Stan · Ionuț G. Stan Over a year ago · @JackFrost yeah, that's right. You're not dumb, you're just learning :) 2016-01-27T14:19:58.993Z+00:00 ... This question is old, but understanding this answer took me way too much time O.o, I think expanding math.random on next JavaScript ... More on stackoverflow.com
🌐 stackoverflow.com
Generate random number between two numbers in JavaScript - Stack Overflow
@Hexodus as far I know, JS not ... - and js will show proper int value) - more here. We also have Uint32array -which means Unsigned Integer 32bit array) 2022-10-02T19:33:15.463Z+00:00 ... Inspite of many answers and almost same result. I would like to add my answer and explain its working. Because it is important to understand its working rather than copy pasting one line code. Generating random numbers is nothing but simple maths... More on stackoverflow.com
🌐 stackoverflow.com
How does Math.random() work in javascript? - Stack Overflow
Why is Google Chrome's Math.random number generator not *that* random? More on stackoverflow.com
🌐 stackoverflow.com
TIL Math.random() is not random enough for a raffle draw, the crowd made sure I was informed of that.

I wouldn't be so sure. It can happen. That's the thing with randomness, it doesn't mean "fairly even distribution across a range", it means "totally unpredictable"

http://dilbert.com/strips/comic/2001-10-25/

However, I'd be looking at your code - what does it look like? Also, what kind of device were you running it on - these can be factors too.

More on reddit.com
🌐 r/javascript
47
11
October 19, 2012
🌐
CoreUI
coreui.io › blog › how-to-generate-a-random-number-in-javascript
Javascript Random - How to Generate a Random Number in JavaScript? · CoreUI
April 16, 2024 - Math.random() is a powerful tool in JavaScript that generates a pseudo-random number—a number that seems random but is actually generated through a deterministic process. It returns a floating-point, or decimal, number between 0 (inclusive) ...
🌐
W3Schools
w3schools.com › jsref › jsref_random.asp
JavaScript Math random() Method
cssText getPropertyPriority() getPropertyValue() item() length parentRule removeProperty() setProperty() JS Conversion · ❮ Previous JavaScript Math Object Next ❯ · let x = Math.random(); Try it Yourself » · Return a random number between ...
Top answer
1 of 16
4922

There are some examples on the Mozilla Developer Network page:

/**
 * Returns a random number between min (inclusive) and max (exclusive)
 */
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

/**
 * Returns a random integer between min (inclusive) and max (inclusive).
 * The value is no lower than min (or the next integer greater than min
 * if min isn't an integer) and no greater than max (or the next integer
 * lower than max if max isn't an integer).
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Here's the logic behind it. It's a simple rule of three:

Math.random() returns a Number between 0 (inclusive) and 1 (exclusive). So we have an interval like this:

[0 .................................... 1)

Now, we'd like a number between min (inclusive) and max (exclusive):

[0 .................................... 1)
[min .................................. max)

We can use the Math.random to get the correspondent in the [min, max) interval. But, first we should factor a little bit the problem by subtracting min from the second interval:

[0 .................................... 1)
[min - min ............................ max - min)

This gives:

[0 .................................... 1)
[0 .................................... max - min)

We may now apply Math.random and then calculate the correspondent. Let's choose a random number:

                Math.random()
                    |
[0 .................................... 1)
[0 .................................... max - min)
                    |
                    x (what we need)

So, in order to find x, we would do:

x = Math.random() * (max - min);

Don't forget to add min back, so that we get a number in the [min, max) interval:

x = Math.random() * (max - min) + min;

That was the first function from MDN. The second one, returns an integer between min and max, both inclusive.

Now for getting integers, you could use round, ceil or floor.

You could use Math.round(Math.random() * (max - min)) + min, this however gives a non-even distribution. Both, min and max only have approximately half the chance to roll:

min...min+0.5...min+1...min+1.5   ...    max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘   ← Math.round()
   min          min+1                          max

With max excluded from the interval, it has an even less chance to roll than min.

With Math.floor(Math.random() * (max - min +1)) + min you have a perfectly even distribution.

 min...  min+1...    ...      max-1... max....   (max+1 is excluded from interval)
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘   ← Math.floor()
   min     min+1               max-1    max

You can't use ceil() and -1 in that equation because max now had a slightly less chance to roll, but you can roll the (unwanted) min-1 result too.

2 of 16
657
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
🌐
V8
v8.dev › blog › math-random
There’s Math.random(), and then there’s Math.random() · V8
Math.random() is the most well-known and frequently-used source of randomness in JavaScript. In V8 and most other JavaScript engines, it is implemented using a pseudo-random number generator (PRNG). As with all PRNGs, the random number is derived from an internal state, which is altered by ...
🌐
HackerNoon
hackernoon.com › how-does-javascripts-math-random-generate-random-numbers-ef0de6a20131
How does JavaScript’s Math.random() generate random numbers? | HackerNoon
March 12, 2018 - Open up your dev tools’ (Mac: cmd + option + i / Windows: ctrl + shift + i), go to the Console, type Math.random() , and hit return.
Find elsewhere
🌐
Udacity
udacity.com › blog › 2021 › 04 › javascript-random-numbers.html
Creating Javascript Random Numbers with Math.random() | Udacity
September 27, 2022 - Javascript is a full programming language, able to make complex mathematical calculations. Learn how you can create random numbers with Math.random()
🌐
SitePoint
sitepoint.com › blog › javascript › how to generate random numbers in javascript with math.random()
Generating Random Numbers in JavaScript with Math.random()
November 7, 2024 - Learn how to use Math.random to generate random numbers in JavaScript and create random colors, letters, strings, phrases, passwords, & more.
🌐
freeCodeCamp
freecodecamp.org › news › javascript-random-number-how-to-generate-a-random-number-in-js
JavaScript Random Number – How to Generate a Random Number in JS
August 3, 2022 - The Math.floor() method will round down the random decimal number to the nearest whole number (or integer). On top of that, you can specify a max number. So, for example, if you wanted to generate a random number between 0 and 10, you would do the following:
🌐
freeCodeCamp
freecodecamp.org › news › how-to-use-javascript-math-random-as-a-random-number-generator
How to Use JavaScript Math.random() as a Random Number Generator
August 24, 2020 - In this guide, you will learn how to generate a random number using the Math.random() method by building a mini dice game.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-generate-random-number-in-given-range-using-javascript
Generate Random Number in Given Range Using JavaScript - GeeksforGeeks
July 11, 2025 - To generate random numbers within predefined ranges, arrays can help organize the ranges and randomize the selections. ... let ranges = [ { min: 5, max: 10 }, { min: 20, max: 25 }, { min: 30, max: 35 } ]; let range = ranges[Math.floor(Math.random() ...
🌐
LaunchCode
education.launchcode.org › intro-to-professional-web-dev › appendices › math-method-examples › random-examples.html
Math.random Examples — Introduction to Professional Web Development in JavaScript documentation
Using the round method gives the widest range, generating numbers between 0 and 10. Rather than trying to remember which method to use, one choice is to ALWAYS use floor to round to an integer: Math.floor(Math.random()*10) generates a number from 0 - 9.
🌐
Keploy
keploy.io › home › community › how to generate random numbers in javascript
How to Generate Random Numbers in JavaScript | Keploy Blog
November 1, 2024 - Learn to generate random numbers, integers, Booleans in JavaScript for different scenarios, from basic to advanced techniques.
🌐
Math.js
mathjs.org › docs › reference › functions › randomInt.html
math.js
math.randomInt() // generate either 0 or 1, randomly math.randomInt(max) // generate a random integer between 0 and max math.randomInt(min, max) // generate a random integer between min and max math.randomInt(size) // generate a matrix with random integer between 0 and 1 math.randomInt(size, ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-math-random-method
JavaScript Math random() Method - GeeksforGeeks
July 15, 2024 - let min = 4; let max = 5; let random = Math.random() * (+max - +min) + +min; console.log("Random Number Generated : " + random);
🌐
GitHub
github.com › ckknight › random-js
GitHub - ckknight/random-js: A mathematically correct random number generator library for JavaScript. · GitHub
A mathematically correct random number generator library for JavaScript. - ckknight/random-js
Starred by 616 users
Forked by 51 users
Languages   TypeScript 94.8% | JavaScript 5.2%
Top answer
1 of 5
35

This answer is outdated. See this answer for a more up-to-date explanation.

Math.random() returns a Number value with a positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy.

Here's V8's implementation:

uint32_t V8::Random() {

    // Random number generator using George Marsaglia's MWC algorithm.
    static uint32_t hi = 0;
    static uint32_t lo = 0;

    // Initialize seed using the system random(). If one of the seeds
    // should ever become zero again, or if random() returns zero, we
    // avoid getting stuck with zero bits in hi or lo by reinitializing
    // them on demand.
    if (hi == 0) hi = random();
    if (lo == 0) lo = random();

    // Mix the bits.
    hi = 36969 * (hi & 0xFFFF) + (hi >> 16);
    lo = 18273 * (lo & 0xFFFF) + (lo >> 16);
    return (hi << 16) + (lo & 0xFFFF);
}

Source: http://dl.packetstormsecurity.net/papers/general/Google_Chrome_3.0_Beta_Math.random_vulnerability.pdf

Here are a couple of related threads on StackOverflow:

  • Why is Google Chrome's Math.random number generator not *that* random?
  • How random is JavaScript's Math.random?
2 of 5
15

See There's Math.random(), and then there's Math.random():

Until recently (up to version 4.9.40), V8’s choice of PRNG was MWC1616 (multiply with carry, combining two 16-bit parts). It uses 64 bits of internal state and looks roughly like this:

uint32_t state0 = 1;
uint32_t state1 = 2;
uint32_t mwc1616() {
  state0 = 18030 * (state0 & 0xffff) + (state0 >> 16);
  state1 = 30903 * (state1 & 0xffff) + (state1 >> 16);
  return state0 << 16 + (state1 & 0xffff);
}

The 32-bit value is then turned into a floating point number between 0 and 1 in agreement with the specification.

MWC1616 uses little memory and is pretty fast to compute, but unfortunately offers sub-par quality:

  • The number of random values it can generate is limited to 232 as opposed to the 252 numbers between 0 and 1 that double precision floating point can represent.
  • The more significant upper half of the result is almost entirely dependent on the value of state0. The period length would be at most 232, but instead of few large permutation cycles, there are many short ones. With a badly chosen initial state, the cycle length could be less than 40 million.
  • It fails many statistical tests in the TestU01 suite.

This has been pointed out to us, and having understood the problem and after some research, we decided to reimplement Math.random based on an algorithm called xorshift128+. It uses 128 bits of internal state, has a period length of 2128 - 1, and passes all tests from the TestU01 suite.

The new implementation landed in V8 4.9.41.0 within a few days of us becoming aware of the issue. It will become available with Chrome 49. Both Firefox and Safari switched to xorshift128+ as well.

The xorshift128+ implementation looks like this:

static inline void XorShift128(uint64_t* state0, uint64_t* state1) {
  uint64_t s1 = *state0;
  uint64_t s0 = *state1;
  *state0 = s0;
  s1 ^= s1 << 23;
  s1 ^= s1 >> 17;
  s1 ^= s0;
  s1 ^= s0 >> 26;
  *state1 = s1;
}