Outputting a random number that falls in a certain range in JavaScript


We are required to write a JavaScript function that takes in a number, say n, and an array of two numbers that represents a range. The function should return an array of n random elements all lying between the range provided by the second argument.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const num = 10;
const range = [5, 15];
const randomBetween = (a, b) => {
   return ((Math.random() * (b - a)) + a).toFixed(2);
};
const randomBetweenRange = (num, range) => {
   const res = [];
   for(let i = 0; i < num; ){
      const random = randomBetween(range[0], range[1]);
      if(!res.includes(random)){
         res.push(random);
         i++;
      };
   };
   return res;
};
console.log(randomBetweenRange(num, range));

Output

The output in the console will be −

[
   '13.25', '10.31',
   '11.83', '5.25',
   '6.28', '9.99',
   '6.09', '7.58',
   '12.64', '8.92'
]

This is just one of the many possible outputs.

Updated on: 21-Oct-2020

69 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements