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

Denise Edwards
Denise Edwards
4,924 Points

I don't understand the math...

This isn't really a programming question, but a math one...

Dave says that this is the basic formula to generate a random number between an upper and a lower range:

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

First of all, he doesn't specify what range this covers (based on everyone else's solutions, I'm assuming that it's between 1 and 6)... but even so, 1) I'm still not sure how this would work with any other range, say between 3 and 5, and 2) how did he come to this solution?

For example, if we were to use the range 3 to 5:

Math.floor(Math.random() * (5 - 3 + 1)) + 1 Math.floor(Math.random() * (2 + 1)) + 1 Math.floor(Math.random() * (3)) + 1 <-- Essentially, we are just generating a random number from 1 to 3.... That doesn't cover 4 or 5 at all this way...

2 Answers

It can be a little confusing at first, but take a look at this link, I think you will find it helpful:

creating random number using JS

Denise Edwards
Denise Edwards
4,924 Points

Thanks Jacob! I missed the second "lower" hahah

This clears everything up!

It's all good. Glad It helped.