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) Working With Numbers The Random Challenge Solution

Random Challenge

Why does line 5 use + bottom number?

Why does line 6, say random number between top number and bottom number?

3 Answers

For line 5 does it make a difference if we place a + 1 inside the operation of var randomNumber = Math.floor(Math.random() * (topNumber - bottomNumber + 1)) + bottomNumber;

But why can't we use + topNumber instead? Would it make much difference? For line 6.

But why can't we use + topNumber instead? Would it make much difference? For line 5 i meant.

Steven Parker
Steven Parker
229,608 Points

By itself, Math.random() creates a random number range starting at 0. Adding the bottom number in the fomula on line 5 changes the minimum value so that the random number will fit in the range asked for.

The message on line 6 is just showing what settings were given to the formula to create the random number.

Steven Parker
Steven Parker
229,608 Points

Adding +1 allows the random number to go up to and including the topNumber. If you leave off the +1, the number created will always be less than the topNumber.

And if you added "topNumber" instead of "bottomNumber", then the random number would be higher than range asked for instead of within it.

Steven Parker
Steven Parker
229,608 Points

For this formula to work correctly, the bottomNumber must be lower than the topNumber. It's possible to write a more complex formula that would work correctly either way, but that's a bit beyond the puprpose of this particular example.

Say if your bottom number is higher than your bottom number? Would have to make some changes to line 5?

So swap + bottom Number for + top Number?