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

How does Math.floor(Math.random() * 6) + 1 work?

I'm trying to understand how this process works:

Math.floor(Math.random() * 6) + 1;

Process:

Math.random() creates a number between 0 - 0.9

The "*6" multiplies random number by 6 - This creates a number between 0 - 5

Example: 0.4 * 6 = 2.4

Math.floor() takes a decimal number and converts it into an integer 2.4 = 2

The +1 is then added to create a number between 1 - 6

If the random number is “0” - it adds 1 to make it 1. if the random number is 5 - it adds 1 to make it 6

Is this thinking correct?

Thanks

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

You're correct. And we can look at the two extremes to prove this. If Math.random() rolls a 0 we take that and multiply it by 0 which gives us 0. Then we floor it, which in this case has no effect. We still have 0. Then we add a 1. That gives us a total of 1.

If Math.random() were to roll 0.9, we take that and multiply it by 6 which gives us 5.4. Then we take the floor of that which is 5. Then we add 1 which gives us a final result of 6. So the random numbers will only ever be between 1 and 6.

Thank you so much, Jennifer. You have cleared that up!