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

Math floor and math random

function alertRandom() {

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

alert(randomNumber); }

math.floor function rounds up anything (0 - .99) that math.random takes out then it will multiply by 6 and then add 1?

1 Answer

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,254 Points

Hi Victor,

The random method actually outputs a random number between 0 and 1 but that has a fixed decimal point number rather than a whole integer value. (i.e. not precisely 1 or 0). So what floor() does is gives us that random value. But it'll always be 0.

So that's what we multiply it by a value 6 and then add 1 to it. Since it always rounds down we won't get a possible 6 output by leaving it as * 6. Adding +1 will allow us to get a possible output of 6.

Hope this helps. :)