JavaScript: How to get a Random Integer Between Two Numbers

In this post, we will fetch a random integer between two numbers we define.

I.E. let’s say we want a random number between 1 and 100. We will use methods from the MATH object to achieve this. More specifically the Random and Floor methods.

Let’s first see what the random method does:

let randomNumber = Math.random();

// randomNumber will be a random floating point between 0 and 1 (just below 1)
// An example would be 0.6299000095102882

We don’t want a floating-point number, but a whole number (integer). To achieve that we can use the floor method. This method will round down to the nearest whole number.

let randomNumber = Math.floor(Math.random());

// randomNumber will always be 0

The problem here is that randomNumber always will return 0. This is because Math.random() will return a number below 1 and then Math.floor() will round down to 0.

So to create a random number between 0 and 99, we need to do this:

let result = Math.floor(Math.random() * 100)

// returns a number between 0 and 99

This will never get to 100 since Math.random() always creates a number below 1. So to get a random number between 1 and 100 we simply add 1 like this:

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

// returns a number between 1 and 100

Similar Posts