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.

Prakhar Patwa
11,260 Pointsi need some help regarding the js code of this function challenge
I entered the code :
var randomNumber = Math.floor( Math.random() * (upper - lower) ) + lower;
in the video i saw that they entered the code : var randomNumber = Math.floor( Math.random() * (upper - lower + 1) ) + lower;
i wonder why they add "1" in the code
my code is still running
2 Answers

Andrew Gay
20,893 PointsWithout the +1 you will never have a random number reach the upper variable passed in.
The floor function will always truncate the value
Math.rand will return a number 0-.9999999*...*
.99999999 * (upper - lower) + lower
Will never reach the upper limit, it will be off by a small decimal
So with the +1 off set the highest value returned will be equivalent to .999999... + upper which is then truncated with Math.floor (Which would then make it the upper.)
The documentations reads:
"The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user."
As you can see the ')' by the 1 means that it will contain every number up until 1 (Not including 1)

Jeff Lemay
14,266 PointsBasically, when your upper limit is set to 100 and your lower limit is set to 1, you add the +1 so that you are finding a random number from 100 possibilities. If you exclude the +1, you will only have 99 possibilities (100-1=99).

Prakhar Patwa
11,260 Pointsthnkx i got the solution
Prakhar Patwa
11,260 PointsPrakhar Patwa
11,260 Pointsthnkx i got the solution