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 JavaScript Basics (Retired) Creating Reusable Code with Functions Random Number Challenge

Amanda Cox
Amanda Cox
3,213 Points

Can someone explain the random number equation?

I am really enjoying JavaScript so far. Everything makes sense until we always inevitably come back to this random number equation. I just can't seem to wrap my head around it. Can someone explain it to me?

The equation is: Math.floor(Math.random() * (6 - 1 + 1)) + 1;

Which from what I understand means: Math.floor(Math.random()*(max-min+1)+min);

Why do we have to do the minus min plus one? Why can't it be Math.floor(Math.random() * 6) + 1

Thanks everyone.

3 Answers

Steven Parker
Steven Parker
229,785 Points

You can simply the function here since "min" is 1 and it cancels out the +1, and I certainly recommend it.

I think it was just shown that way to illustrate the full formula, which would become more important when you had a different "min" value (for example, if you wanted a random number from 10 to 20).

In the formula, "max - min + 1" represents the range, or how many numbers you want to pick from. Using that example, you'd get 20 - 10 + 1 or 11 values (when you include both 10 and 20). But when you multiply by 11 and take the "floor" you'll get a number from 0 to 10, so the final part of the formula adds "min" again which in this case would raise the output to from 10 to 20.

Amanda Cox
Amanda Cox
3,213 Points

Can you explain why it’s needed for a different set of numbers? The challenge in this video asks for any 2 numbers, and I want to understand the theory/logic behind it as well.

Steven Parker
Steven Parker
229,785 Points

I expanded my answer, does it make sense now?