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 Solution

Saqib Ishfaq
Saqib Ishfaq
13,912 Points

how do we know which "1" needs to be replaced with "lower" ? as there are two "1" in the provided formula.

can some one please explain the formula mentioned in the video:/

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

1 Answer

This form returns a random number within a range (inclusive): Math.floor(Math.random() * (upper - lower + 1)) + lower;.

You can reason about a function like this from the inside to the outside according to the parentheses. The inner part is equal to the size of the range (upper - lower + 1).

Math.random() returns some value between 0 and 1, so when you multiply that by the size of the range you get some number between 0 and the size of the range.

Math.floor() returns only the integer part of that result.

Finally, adding the lower number gives a final result randomly within the range size, equal to or larger than the lower number, as required. In plain language you might say, "Give me a number 0, 1 or 2 bigger than 5." In our formula that would be upper=7, lower=5.

Hope that helps! Keep on coding!