Phillip Shim

Posted on

# Working with random numbers in JavaScript

Unpredictable behavior makes our apps more interesting when done right. For example, imagine card games where you get to keep the same set of cards to play every round instead of shuffling them around at the end of each game to receive new cards! We definitely need some kind of randomization to make our life more fun :)

## Math.random()

In JavaScript, we have a built-in method called Math.random(). We won't go into details of how Math.random() is implemented under the hood but let's talk about utilizing Math.random() to generate random numbers we want. Let's first run Math.random() in a console.

``````Math.random() // 0.34484257625111736
``````

Math.random() returns a floating number(number with decimal) between 0 (inclusive) and 1(exclusive). Knowing this behavior, we can set it up so that it scales to the range we want! Let's suppose we want a random integer(number without decimal) between 1 and 10. Here is how we would do this.

``````Math.floor(Math.random() * 10) + 1 // 4
``````

We multiply the output of Math.random() by 10, which will always return a floating number between 0 and 9.9999999... Because 0 times 10 is still 0 and 0.9999999... times 10 is 9.9999999... (Math.random() never reaches 1).

Secondly, we use Math.floor() to round it down to the nearest integer. The output now returns an integer between 0 and 9.

Then, we will add 1 to offset our output! Our formula now generates a number between 1 and 10.

## A better solution?

We could actually shorten our code a little bit by using Math.ceil() instead of Math.floor().

``````Math.ceil(Math.random() * 10) // 8
``````

Math.ceil() takes a number and rounds up to the nearest integer, which acts opposite of Math.floor(). It means there is no longer a need for +1 in the end.

Choose whichever you like, although I've seen the first method more frequently.

## Reusability for the win!

If you have been reading my articles. You know how much I focus on making codes reusable. Using the above technique we learned, let's make a versatile function that takes in a minimum number and a maximum number to put out a number between the range of 2 arguments. Actually, before I code it up for you. Why don't you give it a try as an exercise?

## The steps

Did you get it? Don't worry if you didn't. It's actually pretty hard to wrap your head around it for the first time.

We know Math.random() gives a floating number from 0 to 0.9999999... We also know Math.floor() rounds the number down to the nearest integer. Therefore, `Math.floor(Math.random())` always results in 0. Well, what do we do to get more than one integer as a result? The possible number inside Math.floor() needs to be greater than 1!

Recall that multiplying by 10 to Math.random() gives us 10 possibilities. What if we multiply by 5 or 2?

``````Math.floor(Math.random() * 10) // 0 - 9 (10 possibilities)
Math.floor(Math.random() * 5) // 0 - 4 (5 possibilities)
Math.floor(Math.random() * 2) // 0 - 1 (2 possibilities)
``````

Okay, let's give a scenario and say we want a random integer in the range of 10 and 20. Let's pass in 10 as our min and 20 as our max. That means we need to multiply Math.random() with the difference between the max and the min. Here is what we have so far.

``````function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min))
}
``````

This actually converts to exactly what we had in the beginning for our scenario.

``````Math.floor(Math.random() * (20 - 10)) // 0 - 9 (10 possibilities)
``````

However, we want a few things to be different. Notice that we are now looking for 11 possibilities instead of 10 possibilities because we want to include 10 and 20 (10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20). So let's add 1 to our formula.

``````function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1))
}
``````

Which in our scenario is

``````Math.floor(Math.random() * (20 - 10 + 1)) // 0 - 10 (11 possibilities)
``````

At last, we also care about our range along with the number of possibilities. What do we need to bump up from 0 - 10 to 10 - 20? Adding the min at the end. Here is the solution.

## The solution

``````function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
``````

Our scenario yields

``````Math.floor(Math.random() * (20 - 10 + 1)) + 10 // 10 - 20 (11 possibilities)
``````

## Summary

Math.random() is quite useful and powerful that can be used for many different purposes. From randomly picking a value from a given array to generating a different number on rolling on dice is all done through Math.random(). I hope you get to play with it in near future projects if you haven't had a chance to use it yet. Thanks for reading!

Burak Kucukparmaksiz

Hi Philip,

I am trying to some random number generation, for example, numbers selecting this array => [1 to 9]
numbers generating 9 digits but I want to use each number using just 2 times, not more. How can I do that?

Bhanu Pratap Singh

Now I get it 🙂

Phillip Shim

I am glad you get it!

Jacob Evans

Date.now() * Math.random()

😁

Phillip Shim

Haha nice one!

Juneau Lim

Absolutely didn't know of ceil(). Wow. What have I done until now.
Love the examples. Thank you so much for the post!

Phillip Shim

Of course, thank you for your kind words :)

imsikun

Thank Philip, it's really a good one. Helped me clearing the doubts. Keep it up man

Phillip Shim

Thanks! I am glad it could help :)