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 trialGustavo Reyes
2,458 Pointsfunction 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
231,271 PointsLet's break up the statement into steps:
- upper - lower + 1 first, compute how wide the range should be
- Math.random() * (upper - lower + 1) then multiply by random to get a value in that range
- Math.floor( Math.random() * (upper - lower + 1)) then drop any fractional part to get an integer
- Math.floor(Math.random() * (upper - lower + 1)) + lower 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.
Jason Anello
Courses Plus Student 94,610 PointsHi 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