Get Random value from a range of numbers in JavaScript?


Let’s say, first, we will set the start and end range and call the function:

console.log(getRandomValueBetweenTwoValues(400, 480))

We have passed start value 400 and end value 480. Let’s get the random value with Math.random() in JavaScript −

Example

function getRandomValueBetweenTwoValues(startRange, endRange) {
   return Math.floor(Math.random() * (endRange - startRange + 1) + startRange);
}
console.log(getRandomValueBetweenTwoValues(400, 480))

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo109.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo109.js
401

Updated on: 09-Sep-2020

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements