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

Nour El-din El-helw
Nour El-din El-helw
8,241 Points

Why add 1?

Why should i add 1 in var randomNumber = Math.floor(Math.random() * (topNumber - bottomNumer + 1)) + bottomNumber; that's how i did it and it works well (got it from MDN) https://w.trhou.se/q6sphmij0r

2 Answers

Basically, the function Math.random() gives you a random number between 0 and 1. That means all the float range of 0 to 1 not including 1. When you add Math.floor, you round the number down to the lowest integer, which will always be 0. If you want to get to 1 you would need to add 1.

So if you have something like Math.floor(Math.random() * 6); It will generate a number between 0 and 5 but it will never give you 6. If you want to display 6 as well, you would have to add + 1. Hope that helped. ;)

You add one to get the inclusive range, bottom number to top number. See also this previous question for more analysis of the formula...