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 Numbers The Math Object Random Number Challenge – Two Numbers Solution

Baljit Padda
Baljit Padda
3,694 Points

Struggling to understand how to process a user's lowest number when generating a random number in their specified range.

Hello Treehouse,

I am struggling to understand how you write the code that generates the random number between the range we ask of the user. i.e. if they give the lowest number as 10 and the highest number as 25. Please can you explain this more.

I managed to generate a random number when it was just using a highest number/Max value but could someone please explain how you do this with two user-given values. i.e. how do you know to subtract highest value - lowest value and + 1 etc. ???

Thanks for your help!

Baljit

1 Answer

Steven Parker
Steven Parker
216,810 Points

Starting about 1 minute into the video, the instructor shows and explains changing the code to handle both upper and lower limits.

The highest value - lowest value + 1 part of the formula is how you determine how many possible random values there will be, so you can multiply that by the random function. Then, since the range of random numbers begins at 0, you add the lowest value to shift the range into the desired position.

Baljit Padda
Baljit Padda
3,694 Points

Hi Steven,

Thank you for explaining this further. Thanks for your help! :)