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

The subtraction in the code

in the code

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

specifically the (upper - lower +1)

Why are you subtracting upper from lower than adding one. I how have never known to do this.

2 Answers

Gaurav Yadav
Gaurav Yadav
5,047 Points

It would be easier if you understand this with the help of an example first..then visualize what is going on...if upperVal = 20 and lowerVal = 12, then we need to find a random number in the range [12,20]....when we subtract 12 from 20 we get 8, then we add 1 which gives us 9... So now

Math.floor(Math.random() * (upperVal - loweVal +1 ))

If this code runs we get a random number from 0 to 8 both included, now what was our initial problem? We wanted to get a random number between 12 and 20, but we are getting value between 0 and 8, we consider the extreme cases first, Suppose the above code gives us 0, so if we add 12 (lowerVal) to 0 we get our result...now if the above code gives 8 and we add 12 to it, we get 20 which is what we wanted... all the other case will also be in the range [12,20]. So add lowerVal to the above code and u will get the random number in the range.

Thanks that made a lot of sense. I wish this portion (the subtracting portion), was explained a lil more in detail. Because even after I watched the video of how he built it I was still confused!!! lol

Michiko Yamada
Michiko Yamada
2,325 Points

thank goodness you explained this! i was about to quit! haha!

Jay Mendez
Jay Mendez
2,898 Points

you're a saint, thank you