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 Loops, Arrays and Objects Simplify Repetitive Tasks with Loops `do ... while` Loops

Explain 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Anne Brown
Full Stack JavaScript Techdegree Graduate 20,091 Points

Hi 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?

Yes, thank you very much, Anne!