JavaScript Random Number Tutorial

JavaScript provides the Math module in order to generate random numbers. The Math.random() method is used to generate random numbers between 0 and 1 where 0 is included but 1 is not included. The Math.random() method can be used to generate random numbers as integers and in other forms.

Generate Random Number with Math.random()

The Math.random() method is used to generate a random number between 0 and 1. This is not an integer and it is a floating-point number.

r = Math.random()

Generate Random Integer with Math.random()

JavaScript does not provide a native way to generate random integers. But there are different ways to generate random integers by using the Math.random() and Math.floor() methods. First, we generate a random number between 0 and 1 with the Math.random() method and then multiply it by 10 to make it a floating-point number with an integer. The last step is getting the integer part by using the Math.floor() method.

r = Math.floor(Math.random() * 10);

Generate Random Integer Between Specified Range with Math.random()

We can easily specify the range of the random number by multiplying the result with the range we need. For example, if we want to generate a number between 0 and 100 we should multiply the Math.random() result with 100.

r = Math.floor(Math.random() * 100);
Random Number RangeRandom Number Generation
Between 1 and 10r = Math.floor(Math.random() * 10);
Between 1 and 20r = Math.floor(Math.random() * 20);
Between 1 and 50r = Math.floor(Math.random() * 50);
Between 1 and 100r = Math.floor(Math.random() * 100);
Between 1 and 1000r = Math.floor(Math.random() * 1000);
Between 50 and 100r = Math.floor(Math.random() * 50)+50;

Leave a Comment