Generate Random Number in a specific range in JavaScript

Here we will learn how to generate random number in a specific range in JavaScript.

In JavaScript, we can generate random numbers using it's in-built Math.random() method.

The Math.random() function returns floating-points number between 0 and 1 (inclusive of 0 and exclusive of 1). with uniform distribution over that range.

Since Math.random() returns the number in decimal between 0 and 1. So , we have to multiple it with an integer to set range higher then 1.


// Returns a random integer from 0 to 4 (exclusive of 5)
Math.random() * 5
//output : 4.9878652

You can also see that the max value (here 5) is always excluded in Math.random() results number.

To include the max value in the range we have to add +1 at the end of it.


//To get the random between 1 to 100 (inclusive of 100)
Math.random() * 100 + 1;
//output : 67.9878652

Since the results are in decimal, you can round it up to an integer using Math.floor()method in JavaScript.


 Math.floor(Math.random() * 100 )+ 1; 
 //output: 67

What if the min value is not 0?

To solve that issue, we get the difference between the min and max value and multiple with the the randomly generated number. It will return us an integers.

For example, if we have a range between 1 to 5 then the delta value will be 5-1 i.e 4 so the random number generated will be between 0 and 3.9999.

And now we just have to add the min value to it and it will shift into the right range.

So using Math.random() and Math.floor() we can generate random integers between a specific range.

[Complete code]Generate random numbers in JavaScript within a range.

So here we will code a function which will take two numbers min value and max value(exclusive) and will return use a randomly generated integer.

Exclusive of max value:

function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min) ) + min;

//output: 1 or 2 or 3

Inclusive of the max value:

We just have to add +1 to the difference of max and min value.

function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;

//output: 1 or 2 or 3 or 4 

Related Topics:

3 Ways To Generate Random String/Characters In JavaScript

💾 Recommended Articles