How to generate random number in javascript

Learn how to generate random number in javascript.

We are going to use Math.random() function to get a random number and then use it to generate another random number in any given range.

Math.random() method returns a random number between 0(inclusive) and 1(exclusive), represented as [0, 1) mathematically.

Which means it will return a random number like 0.9621987476689009 between the range 0 and 1 but it will never be 1. As this generated at core level there is very less probability of repeating the same number again.

Input:
console.log(Math.random());

Output:
0.31203509541148966

We can use this randomly generated number along with Math.floor() to generate any random number in any given range.

Formula

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

Generate random number between 1 to 10 in javascript

We will multiply the randomly generated number with maximum - minimum + 1 and add minimum to it and take its floor to get the random number.

console.log(Math.floor((Math.random() * 10) + 1));

//4

Random number between 1 to 100

console.log(Math.floor((Math.random() * 100) + 1));

//20

Generate number between 5 to 25

console.log(Math.floor((Math.random() * (25 - 5 + 1)) + 5));

//23

Or we can create a custom function which will return the random number in any given range specified.

let randomNumber = (min = 0, max = 1) => {
   return Math.floor(Math.random() * (max - min + 1) + min);
}
console.log(randomNumber(85, 95));

//87

Generate random floating numbers in javascript

If we want to generate random number with decimals then there is another formula which can be used.

(Math.random() * (max - min) + min).toFixed(4);

You can update the toFixed to whatever precision you like.

console.log((Math.random() * (5.5 - 4.5) + 4.5).toFixed(4));

//"5.0633"
//"4.9103"
//"4.8354"
//"5.0610"