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 Loops, Arrays and Objects Simplify Repetitive Tasks with Loops `do ... while` Loops

Sandra Vu
Sandra Vu
3,525 Points

Why need to add "+1" to generate the random number?

For example:

Get a random number up to 10

function getRandomNumber(10) { return Math.floor(Math.random()*10)+1; }

All of the similar examples in the video have "+1" in the formula. Why is it the case? Would this alone suffice?

return Math.floor(Math.random()*10)

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Paul Aguilar is correct. Math.random() generates a number between 0 and 1 but not including 1. So if we multiply it by 10 and then take the floor of it, we will only ever get a possible range of 0 to 9.

Adding the one not only increases the upper bound but also the lower bound. So let's say we generated a 0.001. Now when we multiply that by 10 (result: 0.01) and take the floor of that we get a 0. But adding the one guarantees that our lowest number will never be lower than 1. The same is true for .99. If we were to generate a .99 it would be calculated as 9.9. The floor of that is 9 and then we add a 1 which will put our maximum value at 10.

The +1 is there essentially to add one to both our lower bound and upper bound. Hope this helps! :sparkles:

Paul Aguilar
Paul Aguilar
11,053 Points

Math.random() will never actually reach 1 it goes to .99 i believe but will never get to one, and so when you use Math.floor() with it to round down, you would want to add 1 to get to the highest possible number in the range you've selected.

Sandra Vu
Sandra Vu
3,525 Points

Thanks Paul!