Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


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.