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

Dea Kristina
PLUS
Dea Kristina
Courses Plus Student 1,792 Points

why +1?

Why do we have to add '+1' for the : Math.floor(Math.random() * xxx) + 1 ? Is it because we assume that it's a dice that has 1-6 values? If we don't assume a dice, can we just skip the +1 then? Thanks! :)

2 Answers

Steven Ang
Steven Ang
41,751 Points

The Math.floor will remove all the decimal places. Inside the Math.floor function, we use the Math.random to generate random numbers and multiplied it by 6 since it's a die. Remember that just solely using Math.random alone, we will always get numbers below 0 but not 1? That's why we plus it by 1 if we don't you will get numbers between 0 and 5.

Dea Kristina
Dea Kristina
Courses Plus Student 1,792 Points

Thanks! yeah I understand that, but this means that the +1 is because it assumes a dice with 6 values right :)

Ruby Bassi
Ruby Bassi
3,873 Points

I'm wondering the same thing: Is the +1 only relevant if using the die scenario?

jaspergradussen
jaspergradussen
5,876 Points

+1 in Math.floor(Math.random() * xxx) + 1 is to be able to include the original input (being xxx). Say it where 10. I could never be randomly 10 because without +1 it would be a number between 0 and 9.

Because, Math.random() is a number between 0 and <1 and multiply that by 10, you never will be able to get the 10 (0.999999999 * 10 =NOT 10). Include Math.floor() and it makes sure that 9.99999 goes down to 9. So to make it reach 10 in the equation you add a +1.

Ruby Bassi
Ruby Bassi
3,873 Points

that makes total sense. Thanks Jasper Gradussen!