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 JavaScript Basics (Retired) Creating Reusable Code with Functions Random Number Challenge

Gustavo Reyes
Gustavo Reyes
2,458 Points

function getRandomNumber(lower, upper){return Math.floor(Math.random() * (upper - lower + 1)) + lower;}

Can someone explain this function to me in details and all its parameters? Im having a hard time grasping the concept of the conditon in the function . IM not sure how it works

2 Answers

Steven Parker
Steven Parker
231,248 Points

:point_right: Let's break up the statement into steps:

  • upper - lower + 1 :point_left: first, compute how wide the range should be
  • Math.random() * (upper - lower + 1) :point_left: then multiply by random to get a value in that range
  • Math.floor( Math.random() * (upper - lower + 1)) :point_left: then drop any fractional part to get an integer
  • Math.floor(Math.random() * (upper - lower + 1)) + lower :point_left: finally, offset it by the minimum value

So, after all that you have a random number that is an integer and between (inclusive) lower and upper.

Hi Gustavo,

I gave an answer to a similar question which might help you out.

https://teamtreehouse.com/community/mathfloor-mathrandom-max-min-1-min-explanation