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

Prakhar Patwa
Prakhar Patwa
11,260 Points

i 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

Without 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
Jeff Lemay
14,268 Points

Basically, 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).