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 Functions Arrow Functions Function Challenge Solution

What's the point?

I don't understand what's the point to write

Math.floor(Math.random() * (upper - lower + 1)) + 1;

When I get the same results with:

Math.floor(Math.random() * upper) + lower;

2 Answers

Hi Dinu!

The actual formula is:

const rand = Math.floor(Math.random() * (upper - lower + 1)) + lower;

Which give you random numbers between and including the upper and lower values.

Your way:

const rand = Math.floor(Math.random() * upper) + lower;

Produces some values above/higher/larger than upper.

Try it with different upper and lower values, such as 17 and 13, or 20 and 15.

I hope that helps.

Stay safe and happy coding!

why is there a + lower at the end?
const rand = Math.floor(Math.random() * (upper - lower + 1)) + lower;

In all my time here it still doesn't make sense! upper say is 6, - lower say 3 = 3. + 1 = 4 + lower again!! which is now 4+3 = 7??

Thurston Daly
seal-mask
.a{fill-rule:evenodd;}techdegree
Thurston Daly
Full Stack JavaScript Techdegree Student 11,810 Points

Hey jas0n,

You're missing the order of operations and that the formula is multiplying against Math.random() first, which generates a random number using a floating point number. Math.floor() then rounds down the product of Math.random() and (upper - lower + 1) to either the closest lower number or equal to the generated number (if its whole). Lastly, the final + lower is increasing the produced number to be inside the range your upper and lower numbers.