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!

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 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
227,141 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.


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.