Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!