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!

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

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).

We can wrap this all into a function as follows:

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

0 0 vote
Article Rating
Notify of
Inline Feedbacks
View all comments