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 trialErin Didier
6,725 PointsExplain logic of getRandomNumber function
Could someone please explain the logic of the getRandomNumber function step-by-step? Especially why you multiply by the upper and add 1
function getRandomNumber(upper){ var num=Math.floor(Math.random() * upper) +1; return num; }
1 Answer
Anne Brown
Full Stack JavaScript Techdegree Graduate 20,091 PointsHi Erin,
So first, you declare you want to create a function and then name it (getRandomNumber). The upper limit for your random number will be whatever you want to pass in when you call it.
I will explain it kind of inside out for the rest of the function, if that's ok.
The Math.random method returns a value between 0 and 1, but never 1. So you multiply by the upper limit you want your random number to have, to get a broader range, basically. If you just used Math.random, all you'd get would be a number between 0 and 1.
Math.floor is a method in Javascript that rounds down any number, so you if you have 1.6 as your number, it will be rounded down to 1 for the program, if you have 0.2, it will be 0, etc. Since in this case you want your number to never be zero (because for example you want to simulate a dice roll), you have to add 1 at the end.
And then at the end, you want that number you just created to be returned so you can do with it what you need to do.
Does that make sense?
Erin Didier
6,725 PointsErin Didier
6,725 PointsYes, thank you very much, Anne!