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) Working With Numbers The Random Challenge Solution

caleob myers
caleob myers
600 Points

Very confused, need some help please.

var randomNumber = Math.floor(Math.random() * topNumber) +1

I don't understand the * topNumber part. Like how is this creating a random number from 0-5. I'm just very confused.

2 Answers

Tim Strand
Tim Strand
22,458 Points

topNumber is the the max of your range minus the min of your range ie topNumber = 5 - 0; checkout this link on stackoverflow for a more illustrative example and remember google is your friend on this sort of thing. https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range

Math.random() returns 0 - 1 (excluded). F.e. topNumber is 5. You can get 0 - 5 (excluded). The highest number is something like 4.99999999. Math.floor decreases number to nearest lower number. So the result is between 0 and 4. Addition + 1 results in 1 - 5.