JavaScript Code

Generate Random Number Program

Problem Statement

write a JavaScript program with a function that returns a random number between given minimum and maximum values


to generate a random number, 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


1. generate a random number

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