How to Generate Random Numbers in JavaScript

We can generate random numbers in JavaScript by using the Math.random() function. In this tutorial, we will learn how to get random boolean values and then expand on this principle to get random integers between two values.


Random Boolean Values

The Math.random() method returns random decimals somewhere between 0 and 1. To make the number an integer we can then use the Math.round() method which will round the decimal to the nearest integer.


var random_bool = Math.round(Math.random());



In the example above we are getting the output from Math.random() and supplying it directly Math.round() and storing the final result in a variable called random_bool.


Random Integer Between 0 and a Maximum Value

Because Math.random() returns random decimals, we can multiply that result by the maximum value and round it to a whole number. Let's generate a random number between 0 and 10.


var random_number = Math.round(Math.random() * 10);



Random Number Between Two Integers

To get a random number between two values we will create a function that excepts a minimum and a maximum value to get a random integer from.


function getRandomNumber(min, max) {
  return Math.round(Math.random() * (max - min) + min);

var min = 10;
var max = 20;

random_number = getRandomNumber(min, max);



In the getRandomNumber() function, we are multiplying the result of Math.random() by max minus the min then adding min to the result before rounding it to a whole number. The minimum and maximum numbers can be anything, even negative values.



You now know how to generate random numbers in JavaScript in a variety of different ways depending on your needs.

number round random decimal integer