Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max  min + 1) + min)
}
const rndInt = randomIntFromInterval(1, 6)
console.log(rndInt)
What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.

5this is also great because if someone doesn't include the
to
arg, thefrom
arg doubles as the max– JasonFeb 6 '13 at 1:53 
18Hello. This is from MDN:
Returns a floatingpoint, pseudorandom number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.
(developer.mozilla.org/enUS/docs/JavaScript/Reference/…)– FranciscApr 9 '13 at 20:12 
6

5

3Note that this solution is correct only if min and max are integers, otherwise you can get a result in the interval [min, ceil(max)]. I.e. you can get a result which is out of range because is higher than max. Jul 7 '14 at 9:40
Important
The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:
const rndInt = Math.floor(Math.random() * 6) + 1
console.log(rndInt)
Where:
 1 is the start number
 6 is the number of possible results (1 + start (6)  end (1))

51While this would work, @Mike, it would be best to point out the more generic version as Francisc has it below :). Aug 5 '13 at 14:38

701. After Googling I found this question the title is ""Generate random value between two numbers in Javascript"." Won't work if the min value is 0– YdhemOct 8 '13 at 1:44

20Doesn't work if you want a number between two larger numbers eg. Math.floor(Math.random() * 900) + 700– RobNov 25 '13 at 16:12

21That only works if the minimum is 1. If the min is 2 and we still use
Math.floor(Math.random() * 6) + 2
means that ifMath.random()
results into 0.99 our random value would be7
Dec 12 '13 at 16:15 
31This code not good because, does not work with any number. @Francisc code is the correct. Dec 22 '13 at 14:39
Math.random()
Returns an integer random number between min (included) and max (included):
function randomInteger(min, max) {
return Math.floor(Math.random() * (max  min + 1)) + min;
}
Or any random number between min (included) and max (not included):
function randomNumber(min, max) {
return Math.random() * (max  min) + min;
}
Useful examples (integers):
// 0 > 10
Math.floor(Math.random() * 11);
// 1 > 10
Math.floor(Math.random() * 10) + 1;
// 5 > 20
Math.floor(Math.random() * 16) + 5;
// 10 > (2)
Math.floor(Math.random() * 9)  10;
** And always nice to be reminded (Mozilla):
Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

Something that confused me... the Math.floor(..) ensures that the number is an integer where Math.round(..) would give an uneven distribution. Ref: developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/…– alikuliAug 3 '16 at 10:45

1I trust this answer. Can anyone give a link or clear explanation of why this works? Perhaps an example of how Math.round would give a bias, and why that means we have to use this rather complexseeming formula? Oct 11 '16 at 9:05

8@alikuli For a range of
[1,2]
, there is 25% chanceMath.random()
would give you a number from one of these[0,0.49]
,[0.5,0.99]
,[1,1.49]
,[1.5,1.99]
. Rounding those intervals would result in 0, 1, 1, 2 which is not an even distribution. Flooring them results in 0, 0, 1, 1.– pishpishMar 30 '17 at 22:24 
1@shuji This is, among others, the correct answer. I just wanted to clarify why using
Math.round
overMath.floor
would give different results.– pishpishNov 20 '17 at 13:23 
The most accurate solution I've found:
function getRandomInt(min, max) { return Math.round((min  0.5) + Math.random() * (max  min + 1)); }
– SadikMay 23 '20 at 14:34

8would you mind explaining (or giving references to) the ~~ sintaxis? I haven't seen it before! Elegant solution but hard to understand.– DiegoDDMay 31 '13 at 22:49

34Double Tilde
~~a
and Bitwise OR (a  0) are faster ways to write Math.floor(a)– edi9999Jul 18 '13 at 15:39 
8
a  0
is also the fastest and most optimized way to convert a string to an integer. It only works with strings containing integers ("444"
and"444"
), i.e. no floats/fractions. It yields a0
for everything that fails. It is one of the main optimizations behind asm.js.– pilauNov 21 '14 at 7:35 
1

4Note: if you are working with some really large numbers the double tilde is not going to work. Try
~~(Math.random() * (50000000000000  0 + 1)) + 0
andMath.floor(Math.random() * (50000000000000  0 + 1)) + 0
– BrunoLMMay 25 '16 at 23:50
TL;DR
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max + 1  min))
}
To get the random number
generateRandomInteger(20, 20);
EXPLANATION BELOW
We need to get a random integer, say X between min and max.
Right?
i.e min <= X <= max
If we subtract min from the equation, this is equivalent to
0 <= (X  min) <= (max  min)
Now, lets multiply this with a random number r which is
0 <= (X  min) * r <= (max  min) * r
Now, lets add back min to the equation
min <= min + (X  min) * r <= min + (max  min) * r
Now, lets chose a function which results in r such that it satisfies our equation range as [min,max]. This is only possible if 0<= r <=1
OK. Now, the range of r i.e [0,1] is very similar to Math.random() function result. Isn't it?
The Math.random() function returns a floatingpoint, pseudorandom number in the range [0, 1); that is, from 0 (inclusive) up to but not including 1 (exclusive)
For example,
Case r = 0
min
+ 0 * (max
min
) = min
Case r = 1
min
+ 1 * (max
min
) = max
Random Case using Math.random 0 <= r < 1
min
+ r * (max
min
) = X, where X has range of min <= X < max
The above result X is a random numeric. However due to Math.random() our left bound is inclusive, and the right bound is exclusive. To include our right bound we increase the right bound by 1 and floor the result.
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max + 1  min))
}
To get the random number
generateRandomInteger(20, 20)
;
jsfiddle: https://jsfiddle.net/cyGwf/477/
Random Integer: to get a random integer between min
and max
, use the following code
function getRandomInteger(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max  min)) + min;
}
Random Floating Point Number: to get a random floating point number between min
and max
, use the following code
function getRandomFloat(min, max) {
return Math.random() * (max  min) + min;
}
Reference: https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Math/random
Math is not my strong point, but I've been working on a project where I needed to generate a lot of random numbers between both positive and negative.
function randomBetween(min, max) {
if (min < 0) {
return min + Math.random() * (Math.abs(min)+max);
}else {
return min + Math.random() * max;
}
}
E.g
randomBetween(10,15)//or..
randomBetween(10,20)//or...
randomBetween(200,100)
Of course, you can also add some validation to make sure you don't do this with anything other than numbers. Also make sure that min is always less than or equal to max.

5This is simply wrong.
min + Math.random() * max
will give you numbers between min and min+max, which is not what you want. The first branch of theif
is correct, but could be simplified to sayreturn min + Math.random() * (max  min)
, which is the correct solution regardless of whether min is positive or negative (see the other answers). Also, keep in mind that you still need to floor the result if you don't want fractions.– AvishMay 23 '13 at 16:09
ES6 / Arrow functions version based on Francis' code (i.e. the top answer):
const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max  min + 1) + min);

1Nice! It is much useful to provide the
min
andmax
values. I was looking for this answer.– VictorMay 17 at 18:19
I wrote more flexible function which can give you random number but not only integer.
function rand(min,max,interval)
{
if (typeof(interval)==='undefined') interval = 1;
var r = Math.floor(Math.random()*(maxmin+interval)/interval);
return r*interval+min;
}
var a = rand(0,10); //can be 0, 1, 2 (...) 9, 10
var b = rand(4,6,0.1); //can be 4.0, 4.1, 4.2 (...) 5.9, 6.0
Fixed version.

This is not a good solution as it won't work with zero as min value. See @Lior's answer. Sep 11 '15 at 9:45

1Of course it works with zero as min value. Did you try? There is no reason why it might not work. It won't work with 0 as interval which isn't strange (interval = 0?...). Sep 14 '15 at 10:01

I ran multiple times this function with zero as min value and never obtained zero in the output. Or I'm not lucky enough... Sep 14 '15 at 10:11

You are right. "+interval" was in wrong place. Test it now please. Strange thing that sometimes console.log gives me 0.300000004 instead of 0.3 like 3*0.1 wouldn't be exactly 0.3. Sep 14 '15 at 10:40
Example
Return a random number between 1 and 10:
Math.floor((Math.random() * 10) + 1);
The result could be:
3
Try yourself: here

or using lodash / undescore:
_.random(min, max)

1so you need 9 or 10 right? If yes: const randomNumber = Math.floor((Math.random() * 10) + 1) const nineOrTen = randomNumber % 2 === 0 ? 9 : 10 Aug 2 '18 at 14:20
I was searching random number generator written in TypeScript and I have written this after reading all of the answers, hope It would work for TypeScript coders.
Rand(min: number, max: number): number {
return (Math.random() * (max  min + 1)  0) + min;
}
This supports negative integers:
Math.floor(Math.random() * (max  min + 1)) + min;
A simple one liner:
Math.floor( Math.random() * MAX_NUMBER ) + MIN_NUMBER
Eg:
Math.floor( Math.random() * 6 ) + 1
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.
CODE:
function getR(lower, upper) {
var percent = (Math.random() * 100);
// this will return number between 099 because Math.random returns decimal number from 00.9929292 something like that
//now you have a percentage, use it find out the number between your INTERVAL :upperlower
var num = ((percent * (upper  lower) / 100));
//num will now have a number that falls in your INTERVAL simple maths
num += lower;
//add lower to make it fall in your INTERVAL
//but num is still in decimal
//use Math.floor>downward to its nearest integer you won't get upper value ever
//use Math.ceil>upward to its nearest integer upper value is possible
//Math.round>to its nearest integer 2.4>2 2.5>3 both lower and upper value possible
console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}
The top rated solution is not mathematically correct as same as comments under it > Math.floor(Math.random() * 6) + 1
.
Task: generate random number between 1 and 6.
Math.random()
returns floating point number between 0 and 1 (like 0.344717274374 or 0.99341293123 for example), which we will use as a percentage, so Math.floor(Math.random() * 6) + 1
returns some percentage of 6 (max: 5, min: 0) and adds 1. The author got lucky that lower bound was 1., because percentage floor will "maximumly" return 5 which is less than 6 by 1, and that 1 will be added by lower bound 1.
The problems occurs when lower bound is greater than 1. For instance, Task: generate random between 2 and 6.
(following author's logic)
Math.floor(Math.random() * 6) + 2
, it is obviously seen that if we get 5 here > Math.random() * 6
and then add 2, the outcome will be 7 which goes beyond the desired boundary of 6.
Another example, Task: generate random between 10 and 12.
(following author's logic)
Math.floor(Math.random() * 12) + 10
, (sorry for repeating) it is obvious that we are getting 0%99% percent of number "12", which will go way beyond desired boundary of 12.
So, the correct logic is to take the difference between lower bound and upper bound add 1, and only then floor it (to substract 1, because Math.random()
returns 0  0.99, so no way to get full upper bound, thats why we adding 1 to upper bound to get maximumly 99% of (upper bound + 1) and then we floor it to get rid of excess). Once we got the floored percentage of (difference + 1), we can add lower boundary to get the desired randomed number between 2 numbers.
The logic formula for that will be: Math.floor(Math.random() * ((up_boundary  low_boundary) + 1)) + 10
.
P.s.: Even comments under the toprated answer were incorrect, since people forgot to add 1 to the difference, meaning that they will never get the up boundary (yes it might be a case if they dont want to get it at all, but the requirenment was to include the upper boundary).
Math.random()
is fast and suitable for many purposes, but it's not appropriate if you need cryptographicallysecure values (it's not secure), or if you need integers from a completely uniform unbiased distribution (the multiplication approach used in others answers produces certain values slightly more often than others).
In such cases, we can use crypto.getRandomValues()
to generate secure integers, and reject any generated values that we can't map uniformly into the target range. This will be slower, but it shouldn't be significant unless you're generating extremely large numbers of values.
To clarify the biased distribution concern, consider the case where we want to generate a value between 1 and 5, but we have a random number generator that produces values between 1 and 16 (a 4bit value). We want to have the same number of generated values mapping to each output value, but 16 does not evenly divide by 5: it leaves a remainder of 1. So we need to reject 1 of the possible generated values, and only continue when we get one of the 15 lesser values that can be uniformly mapped into our target range. Our behaviour could look like this pseudocode:
Generate a 4bit integer in the range 116.
If we generated 1, 6, or 11 then output 1.
If we generated 2, 7, or 12 then output 2.
If we generated 3, 8, or 13 then output 3.
If we generated 4, 9, or 14 then output 4.
If we generated 5, 10, or 15 then output 5.
If we generated 16 then reject it and try again.
The following code uses similar logic, but generates a 32bit integer instead, because that's the largest common integer size that can be represented by JavaScript's standard number
type. (This could be modified to use BigInt
s if you need a larger range.) Regardless of the chosen range, the fraction of generated values that are rejected will always be less than 0.5, so the expected number of rejections will always be less than 1.0 and usually close to 0.0; you don't need to worry about it looping forever.
const randomInteger = (min, max) => {
const range = max  min;
const maxGeneratedValue = 0xFFFFFFFF;
const possibleResultValues = range + 1;
const possibleGeneratedValues = maxGeneratedValue + 1;
const remainder = possibleGeneratedValues % possibleResultValues;
const maxUnbiased = maxGeneratedValue  remainder;
if (!Number.isInteger(min)  !Number.isInteger(max) 
max > Number.MAX_SAFE_INTEGER  min < Number.MIN_SAFE_INTEGER) {
throw new Error('Arguments must be safe integers.');
} else if (range > maxGeneratedValue) {
throw new Error(`Range of ${range} (from ${min} to ${max}) > ${maxGeneratedValue}.`);
} else if (max < min) {
throw new Error(`max (${max}) must be >= min (${min}).`);
} else if (min === max) {
return min;
}
let generated;
do {
generated = crypto.getRandomValues(new Uint32Array(1))[0];
} while (generated > maxUnbiased);
return min + (generated % possibleResultValues);
};
console.log(randomInteger(8, 8)); // 2
console.log(randomInteger(0, 0)); // 0
console.log(randomInteger(0, 0xFFFFFFFF)); // 944450079
console.log(randomInteger(1, 0xFFFFFFFF));
// Error: Range of 4294967296 covering 1 to 4294967295 is > 4294967295.
console.log(new Array(12).fill().map(n => randomInteger(8, 12)));
// [11, 8, 8, 11, 10, 8, 8, 12, 12, 12, 9, 9]

2@2xSamurai There, I updated the answer to explain why you might need this and how it works. Is that better? :P– JeremyApr 5 '19 at 19:38

1It's not an overkill at all if you want cryptographically secure and uniformly distributed random numbers. Generating random numbers that meet those requirements is hard. Great answer, @JeremyBanks. Dec 25 '19 at 10:25
Adding float
with fixed precision version based on the int
version in @Francisc's answer:
function randomFloatFromInterval (min, max, fractionDigits) {
const fractionMultiplier = Math.pow(10, fractionDigits)
return Math.round(
(Math.random() * (max  min) + min) * fractionMultiplier,
) / fractionMultiplier
}
so:
randomFloatFromInterval(1,3,4) // => 2.2679, 1.509, 1.8863, 2.9741, ...
and for int answer
randomFloatFromInterval(1,3,0) // => 1, 2, 3
This function can generate a random integer number between (and including) min and max numbers:
function randomNumber(min, max) {
if (min > max) {
let temp = max;
max = min;
min = temp;
}
if (min <= 0) {
return Math.floor(Math.random() * (max + Math.abs(min) + 1)) + min;
} else {
return Math.floor(Math.random() * (max  min + 1)) + min;
}
}
Example:
randomNumber(2, 3); // can be 2, 1, 0, 1, 2 and 3
randomNumber(5, 2); // can be 5, 4, 3 and 2
randomNumber(0, 4); // can be 0, 1, 2, 3 and 4
randomNumber(4, 0); // can be 0, 1, 2, 3 and 4



1I think your answer is good in "theory" but it would be much better if you could clearly state in your answer if max = 6 would "include" the possibility of 6 or not, and if min = 1 would "include" the possibility of 1? This can be read very ambiguously, and might confuse people. Is it "max 6  including 6" or "max 6  not including 6"... Same for "min".– mesqueebSep 18 '20 at 4:53

I updated my answer to remove ambiguity and add the possibility of negative numbers. Sep 18 '20 at 15:04

Using random function, which can be reused.
function randomNum(min, max) {
return Math.floor(Math.random() * (max  min + 1)) + min;
}
randomNum(1, 6);
This should work:
const getRandomNum = (min, max) => Math.floor(Math.random() * (max  min + 1)) + min
Cryptostrong random integer number in range [a,b] (assumption: a < b )
let rand= (a,b)=> a+(ba+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**320
console.log( rand(1,6) );
This is about nine years late, but randojs.com makes this a simple oneliner:
rando(1, 6)
You just need to add this to the head of your html document, and you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.
<script src="https://randojs.com/1.0.0.js"></script>
Try using:
function random(min, max) {
return Math.round((Math.random() *( Math.abs(max  min))) + min);
}
console.log(random(1, 6));
If the starting number is 1, as in your example (16), you can use Math.ceil() method instead of Math.floor().
Math.ceil(Math.random() * 6)
instead of
Math.floor(Math.random() * 6) + 1
Let's not forget other useful Math methods.
I discovered a great new way to do this using ES6 default parameters. It is very nifty since it allows either one argument or two arguments. Here it is:
function random(n, b = 0) {
return Math.random() * (bn) + n;
}
This works for me and produces values like Python's random.randint standard library function:
function randint(min, max) {
return Math.round((Math.random() * Math.abs(max  min)) + min);
}
console.log("Random integer: " + randint(5, 5));
Get a random integer between 0 and 400
var rand = Math.round(Math.random() * 400);
console.log(rand);
Get a random integer between 200 and 1500
var range = {min: 200, max: 1500},
delta = range.max  range.min,
rand = Math.round(range.min + Math.random() * delta);
console.log(rand);
Math.floor((Math.random()*10)+1);
cannot work for you as specified here at w3schools.com/jsref/jsref_random.asp ..?