Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Random Number generator

function random (lower, upper){ var random = Math.floor(Math.random() * (upper - lower + 1 )) + lower; }

Can anyone explain me the random number generator? how this block of code is working? Why I have to add 1 after (upper - lower) and add lower number again at the last? I'm confused need explanation.

2 Answers

Math.random() gives a number from and including 0 to and not including 1. This means that the following code gives a random number from 0-5

var randomNumberBetween0And5 = Math.floor(Math.random() * 6)

This is because Math.random() * 6 can vary from 0 (Math.random() = 0) to 5.999 (Math.random() = 0.9999), and when rounding down using Math.floor this becomes 0-5.

We would now like a lower bound, so let's say we want the numbers from 1-6 instead, we could then do the following:

var randomNumberBetween1And6 = Math.floor(Math.random() * 6) + 1

In this case 1 is the lower bound, but this works for any lower bound.

Now I will explain this:

(upper - lower + 1 )

We can see why this is the case by looking at our example above, where we want the numbers from 1-6. This means that upper=6 and lower=1, which means that upper-lower=5, i.e, the random value would be between 1-5, which means that 6 is not included. Therefore we add 1, such that we include the upper value, which in this case was 6.

Thanks