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

M Khan
M Khan
7,024 Points

Not pretty clear of the concept about + 1 after Math.random function

var randomNumber = Math.floor(Math.random() * topNumber) + 1;

Can you pls explain about adding + 1 to the Math.random function

3 Answers

Robert Stewart
Robert Stewart
11,921 Points

Because the Math.floor() function will always round down so, if your user enters 2 and you multiply that against the random number 0.49 you'll get 0.98 which then gets rounded down to 0. However, the point is to simulate a random number between 1 and whatever number the user enters so 0 is not allowed. This is a preventative step to ensure the number is never zero. Note: Math.random() generates a number between 0 and 1.

I hope that clears some things up.

Alexandra Edwards
Alexandra Edwards
4,686 Points

Math.random generates a number from 0 up to, but not including 1. Since Math.floor rounds down, it is possible to generate the number 0. To prevent that from happening, you add 1 so if the random number rounded down turns out to be 0, the +1 will change 0 to 1. Does that help?

To elaborate to Alexandra Edwards. +1 is added in case the user inputs a zero. By doing so you generate a random number regardless of what the input is. If zero is the input, and Math.random generates a number from 0 and up, but not including 1, then the zero becomes 1 because we added +1 and so the program generates a number between 0 and 1, but if you dont specify that, then the program will not generate a random number because a number from 0 to 0 will always be zero.