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.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops What are Loops?

Can someone explain how this returns a random number between 1- 6?

function randomNumber(upper) { return Math.floor( Math.random() * upper ) + 1; } randomNumber ( 6 );

1 Answer

Steven Parker
Steven Parker
210,424 Points

Let's look at the process step-by-step:

  • by calling the function with "6" as the parameter, then "upper" will have the value of 6.
  • the Math.random() function will give you a number somewhere between 0 and 1 (exclusive)
  • multiplying this number by 6 will give you a number between 0 and 6 (exclusive)
  • then the floor function takes away any fractional part, leaving an integer from 0 to 5 (inclusive)
  • finally when you add 1 you have a number from 1 to 6

It's interesting that just spending some time away from the computer allowed me to completely understand the above.

THANK YOU SO MUCH!!!

It's so simple I feel embarrassed that I asked the question... LOL

James March
James March
7,921 Points

Thanks for the thought-out and well structured response Steven. Really helpful.