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
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 floating-point number between 0 (inclusive) and 1 (exclusive).
Discussions

Generating random whole numbers in JavaScript in a specific range - Stack Overflow
If you want max to be inclusive you could use Math.round. 2019-04-08T10:19:49.617Z+00:00 ... Like many other answers here, this doesn't answer the question (my emphasis): "How can I generate random whole numbers between two specified variables in JavaScript, e.g. More on stackoverflow.com
🌐 stackoverflow.com
Basic JavaScript - Generate Random Whole Numbers with JavaScript
Tell us what’s happening: The instructions for this lesson ask you to use the Math.floor(Math.random()) * N to generate and return a random whole number between 0 and 9 When I return Math.floor(Math.random()*9) it is not accepted. The error says " You should have multiplied the result of ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
April 18, 2023
Generate A Random Number Within A Range - How Does the Math Work?
Math.floor() is the floor function. Which means it returns the integer part of a number. In your example Math.floor(5.94) = 5 More on reddit.com
🌐 r/learnprogramming
8
0
February 4, 2022
javascript - Math.random() - Not random - Stack Overflow
There is no way you can change the seed for Math.random() in Javascript. It seeds it using the current time when the script starts executing. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Javascript-coder
javascript-coder.com β€Ί calculation β€Ί javascript-math-random
About Javascript Math.random usage, sample code and more | JavaScript Coder
Math.random() is a built-in JavaScript method that generates a pseudo-random number between 0 and 1 (exclusive).
🌐
DEV Community
dev.to β€Ί jesterxl β€Ί seeing-javascript-mathrandom-not-be-so-random-1235
Seeing JavaScript Math.random Not Be So Random - DEV Community
February 5, 2023 - Context: β€œIf you run Math.random enough between 1 & 6, you’re most likely to get 3.5”. ... Article which helped get me some code: https://questsincode.com/posts/monte-carlo-simulation-javascript
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;
🌐
Oreate AI
oreateai.com β€Ί blog β€Ί harnessing-the-power-of-mathrandom-in-javascript β€Ί 6a57408f9da95749f0f4eb0bfe2c29af
Harnessing the Power of Math.random() in JavaScript - Oreate AI Blog
January 8, 2026 - How do you ensure that every experience feels fresh and unpredictable? Enter Math.random()β€”a simple yet effective function in JavaScript that generates pseudo-random numbers between 0 (inclusive) and 1 (exclusive).
Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org β€Ί javascript
Basic JavaScript - Generate Random Whole Numbers with JavaScript - JavaScript - The freeCodeCamp Forum
April 18, 2023 - Tell us what’s happening: The instructions for this lesson ask you to use the Math.floor(Math.random()) * N to generate and return a random whole number between 0 and 9 When I return Math.floor(Math.random()*9) it is…
🌐
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) ...
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί javascript β€Ί javascript-math-random-method
JavaScript Math random() Method - GeeksforGeeks
July 15, 2024 - The JavaScript Math.random() function gives you a random number between 0 and just under 1. You can use this number as a base to get random numbers within any range you want.
🌐
Math.js
mathjs.org β€Ί docs β€Ί reference β€Ί functions β€Ί random.html
math.js | an extensive math library for JavaScript and Node.js
Return a random number larger or equal to min and smaller than max using a uniform distribution. math.random() // generate a random number between 0 and 1 math.random(max) // generate a random number between 0 and max math.random(min, max) // generate a random number between min and max ...
🌐
W3Schools
w3schools.com β€Ί js β€Ί js_math.asp
JavaScript Math Object
Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):
🌐
Reddit
reddit.com β€Ί r/learnprogramming β€Ί generate a random number within a range - how does the math work?
r/learnprogramming on Reddit: Generate A Random Number Within A Range - How Does the Math Work?
February 4, 2022 -

Hi all,

I'm learning JS through FCC and it's going okay so far. I'm not a very mathematically inclined person, however, so I struggle with some concepts.

I'm struggling to understand how the following code works;

Math.floor(Math.random() * (max - min + 1)) + min

I tried writing out an example on paper and used 10 and 5 as max and min respectively.

Math.floor(Math.random() * (10 - 5 + 1)) + 5

wouldn't this mean that I can get numbers higher than the max though? Say I get a randomly generated 0.99; well 0.99 * (6) + 5 = 10.94 which is greater than my max of 10?

Am I doing this wrong?

🌐
Udacity
udacity.com β€Ί blog β€Ί 2021 β€Ί 04 β€Ί javascript-random-numbers.html
Creating Javascript Random Numbers with Math.random() | Udacity
September 27, 2022 - Javascript creates pseudo-random numbers with the function Math.random(). This function takes no parameters and creates a random decimal number between 0 and 1.
🌐
Zustand
zustand.docs.pmnd.rs β€Ί reference β€Ί apis β€Ί create
create - Zustand
import { create } from 'zustand' const usePositionStore = create<{ x: number y: number }>()(() => ({ x: 0, y: 0 })) const setPosition: typeof usePositionStore.setState = (nextPosition) => { usePositionStore.setState(nextPosition) } export default function MovingDot() { const position = usePositionStore() return ( <div style={{ position: 'relative', width: '100vw', height: '100vh', }} > <div style={{ position: 'absolute', backgroundColor: 'red', borderRadius: '50%', transform: `translate(${position.x}px, ${position.y}px)`, left: -10, top: -10, width: 20, height: 20, }} onMouseEnter={(event) => { const parent = event.currentTarget.parentElement const parentWidth = parent.clientWidth const parentHeight = parent.clientHeight setPosition({ x: Math.ceil(Math.random() * parentWidth), y: Math.ceil(Math.random() * parentHeight), }) }} /> </div> ) }
Top answer
1 of 4
2

The random number function is an equation that simulates being random, but, it is still a function. If you give it the same seed the first answer will be the same.

You could try changing the seed, and do this when the javascript is first loaded, so that if there is a time component to the random number generator, then it can use the delays of pages being loaded to randomize the numbers more.

But, you may want to change the seed. You can use the Date() function, then get the milliseconds and use that as the seed, and that may help to scramble it up first.

My thought that there is a time component to the generator is the fact that it changes with an alert, as that will delay when the next number is generated, though I haven't tested this out.

UPDATE:

I realize the specification states that there is no parameter for Math.random, but there is a seed being used.

I came at this from C and then Java, so the fact that there was no error using an argument led me to think it used it, but now I see that that was incorrect.

If you really need a seed, your best bet is to write a random number generator, and then Knuth books are the best starting point for that.

2 of 4
-2

This is how I solved it for my needs. In my case it works just fine because I will only be requesting numbers sporadically and never sequentially or in a loop. This won't work if you use it inside a loop since it's time based and the loop will execute the requests just milliseconds apart.

function getRandomNumber(quantity_of_nums){
    var milliseconds = new Date().getMilliseconds();
    return Math.floor(milliseconds * quantity_of_nums / 1000);
}

This will give you a number from 0 to quantity_of_nums - 1

Hope it helps!

🌐
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.
🌐
Biome
biomejs.dev
Biome, toolchain of the web
Biome is a fast formatter for JavaScript, TypeScript, JSX, TSX, JSON, HTML, CSS and GraphQL that scores 97% compatibility with Prettier, saving CI and developer time. Biome can even format malformed code as you write it in your favorite editor. CODE Β· 1 Β· function HelloWorld({greeting = "hello", greeted = '"World"', silent = false, onMouseOver,}) { 2 Β· 3 Β· if(!greeting){return null}; 4 Β· 5 Β· // TODO: Don't use random in render Β· 6 Β· let num = Math.floor (Math.random() * 1E+7).toString().replace(/.d+/ig, "") 7 Β·
🌐
Medium
dwisecar.medium.com β€Ί how-math-random-works-in-javascript-2864e1cb772d
How Math.random() works in Javascript | by Dave Wisecarver | Medium
January 27, 2021 - ... According to the ECMAScript 2021 Language Specification: 21.3.2.27 Math.random returns a number value with positive sign, greater than or equal to 0 but strictly less than 1, chosen randomly or pseudo randomly with approximately uniform ...