js random number between 1 and 10
js random number between 1 and 10

Hi Guys, Welcome to Proto Coders Point, In this short article let’s checkout how to generate a random number between 1 and 10 or between any range you want iun javascript.

In JavaScript, To generate a random number between 1 and 10, we can make use of Math.random() function and by applying a bit of math operation.

Basically ‘Math.random()’ function will generate a random decimal floating number range from 0.0 to 1.0 and thus we need to multiple the generate number by 10 and round it to the nearst integer number by using Math.floor() function.

Here is a example

var rand = Math.random();
console.log(rand);  //0.7520321036592579

let random_number = Math.floor(rand * 10) + 1;
console.log(random_number); // 8

In above code, Math.random() function will generate random number from 0.0 to 1.0 [ 0.7520… is the generated number], then to make it range between 1 – 10 I am multiply it with 10 and add 1 to it because math.floor will round to 1 – 9.

Javascript random number between 1 and 100

Now say you want to generate a number between 1 to 100, so can we acheived by just modifying the scaling and shift value i.e just be multiplying the random number generated by 100 and adding 1 to it . For example:

let randomNumber = Math.floor(Math.random() * 100) + 1;