Generate Random Number Program
In this tutorial, you write a JavaScript program with a function that returns a random number between given minimum and maximum values.
Solution
To generate a random number in JavaScript, we can use Math.random()
method. by default, the method returns a value between 0 and 1. We can use this value to translate it into a number between given range of minimum and maximum values.
Program
1. In the following program, we write a function getRandomNumber()
, and generate some random numbers using this function.
function getRandomNumber(min=0, max=1) {
var randNum = min + (max - min) * Math.random();
randNum = Math.round(randNum);
return randNum;
}
console.log(getRandomNumber(10, 20));
console.log(getRandomNumber(100, 1000));
We have used Math.random()
and Math.round()
functions. Math.random()
returns a floating point number between 0 and 1. Math.round()
rounds the given number to the nearest integer, and returns the value.