How to create a random number between a range JavaScript


Our job is to create a function, say createRandom, that takes in two argument and returns a pseudorandom number between the range (max exclusive).

The code for the function will be −

Example

const min = 3;
const max = 9;
const createRandom = (min, max) => {
   const diff = max - min;
   const random = Math.random();
   return Math.floor((random * diff) + min);
}
console.log(createRandom(min, max));

Understanding the code −

  • We take the difference of max and min
  • We create a random number
  • Then we multiply the diff and random to produce random number between 0 and diff
  • Then we add min to it to produce the random number between min and max

Output

Output for this code in the console will be −

6

Updated on: 19-Aug-2020

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements