Generate a random number between two numbers in JavaScript

If you need to generate a random number between two numbers in JavaScript, then you are in the right place! Here you will learn javascript random number generation.

We can easily do this by using a combination of built-in Math functions.

Javascript Random Number from Math.random()

Let’s start by using Math.random() to generate a random number. Now we will take that and multiply it by max - min + 1.

Because of how the Math.random() function works, we will need to then add the minimum value to this.

Once we are done, we pass it through a Math.floor() to get an absolute integer value (not a float).

Code example for Javascript Random Numbers

We can wrap this all into a function as follows:

var generateRandomNumberBetween = function(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);

Notify of
Inline Feedbacks
View all comments