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

Don't understand Math.floor / Math.random

I don't understand why we multiply by 6 here in order to have a number between 1 and 6. I know that Math.random is from 0 to 1 except 1 and math.floor rounds floats to interigers but don't get where the *6 is from.

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

1 Answer

Hi, you can take 6 as a value u want to multiple your outcome of Math.random(), e.g if you want a given month, and you know months in a year are 12, so you can do

var randomMonth = Math.floor(Math.random() * 12) + 1;

and each time you call it, you will get a randomMonth between 0 to 11, and you add + 1 to make it a 12. Basically it is what you want that result of Math.random to multiplied with.

Hope it helps.