Related Tags

javascript
communitycreator

# How to generate a random number between a range in JavaScript

Programming Bytes

In JavaScript, the Math.random function will generate a random floating point number between 0 and 1(0 is included 1 is excluded):

Math.random();


## Generate a random number with a Max limit

Let’s say we need to generate a random number under 100. To do this, we would multiply the random number by 100. Math.random() will not return 1, so the value will be below 100.

Math.random() * 100; // 84.06448370345245


We can use Math.floor to round it down as shown here:

function generateRandom(maxLimit = 100){
let rand = Math.random() * maxLimit;
console.log(rand); // say 99.81321410836433

rand = Math.floor(rand); // 99

return rand;
}
generateRandom(); // 43
generateRandom(500); // 165

## Generate a random number between two numbers

In this case, we will have a MIN and a MAX value and will need to include the MIN value and exclude the MAX value.

If the MIN value is always 0, then we can multiply the random number with the MAX value, but if the MIN value is other than 0, we need to find the difference between MAX and MIN. Then we will multiply the random number with that difference and add the MIN value.

• Let’s say MIN = 3 & MAX = 5.
• Difference is MAX - MIN = 2.
• Upon multiplying a random number by 2, we will get a value between 0 and below 2. So, the possible value will be either 0 or 1.
• When we add the MIN(3) value to the random number, the result is either 3 or 4. We can see this as follows:
function generateRandom(min = 0, max = 100) {

// find diff
let difference = max - min;

// generate random number
let rand = Math.random();

// multiply with difference
rand = Math.floor( rand * difference);

rand = rand + min;

return rand;
}

console.log(generateRandom());

The above can be also be written as:

const random = (min, max) => Math.floor(Math.random() * (max - min)) + min;


RELATED TAGS

javascript
communitycreator

CONTRIBUTOR

Programming Bytes
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 