DEV Community

Arno Volts
Arno Volts

Posted on

Generating random numbers with Math.random() (JS)

Lets begin by understanding what the Math.random() function
does. When called it returns a pseudo-random number in the range [0, 1[. This means that the possible values are between 0 and +- 0.9999, Never 1.

There are some clever tricks we can use in order to change that range. For example if we want to generate numbers between 0 and n.

We can call the Math.random() function and multiply the returned value by n.

Math.random() * n;

note: The result will never be n.

This works well but the result of this expression will be a floating point number. What if we want whole numbers instead ?

Thankfully the Math object has methods that allows to round up or down. For this example I will use the Math.floor() function but feel free to explore the Math object for alternatives.

Our code will look like this:

Math.floor(Math.random() * n);

This code snippet will produce random whole numbers that range from [0, n[.

Lets explore how to generate numbers between an interval such as [4, 10[.

So far we have seen that if want to change the range of Math.random() all we have to is multiply its returned value by n. This time we have two values a max representing the upper bound of the interval and a min representing the lower bound of the interval.

let max = 10;
let min = 4;
Enter fullscreen mode Exit fullscreen mode

What we want is to generate the following numbers:

  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

By doing some simple math we know that there are 6 numbers between 4 and 10 (10 - 4). We could use this knowledge in our expression like so.

Math.floor(Math.random() * (max - min));

We are not done yet because this expression will only
produce numbers between 0 and 6 not 4 and 10 (exclusive).

The possible numbers so far are:

  • 0
  • 1
  • 2
  • 3
  • 4
  • 5

Take a second here to try and figure out how to solve
this problem.

It turns out that if we simply add min to the result
of this expression we can effectively change the range to be what we want:

  • 0 + 4 = 4
  • 1 + 4 = 5
  • 2 + 4 = 6
  • 3 + 4 = 7
  • 4 + 4 = 8
  • 5 + 4 = 9

As you can see here the resulted range is between [4, 10[ .
So in code it will look like this:

Math.floor(Math.random() * (max - min)) + min;

Easy-peasy.

One thing we did not address is what if we want the upper bound of our interval to be included.

All we have to do is add 1 the result of the (max - min) expression. in my example I used 10 and 4.
subtracting them gives us 6 we add to that 1. The result will be 7. This increases the range by 1, allowing us to include our max value in our range.

The final code looks like this:

let max = 10;
let min = 4;

Math.floor(Math.random() * (max - min + 1)) + min;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)