Computer >> Computer tutorials >  >> Programming >> Javascript

Random whole number between two integers JavaScript


We are required to write a JavaScript function that takes in an array of exactly two numbers, specifying a range.

The function should generate a random whole number that falls inside the range (both inclusive) specified as the argument.

Example

const range = [5, 15];
const randomBetween = ([min, max]) => {
   // +1 to include the max range const random = Math.random() * (max - min + 1);
   const whole = Math.floor(random) + min;
   return whole;
};
for(let i = 0; i < 10; i++){
   console.log(randomBetween(range));
}

Output

And the output in the console will be −

13
10
6
10
12
5
14
13
11
6

This output is likely to change on each run.