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

Function

Hello i'm still just learning JS. When i saw this function in a video it confused me. I asked about this before some guy explained it to me in a complicated way. Can someone simply explain it to me?. function getRandomNumber(upper) { return Math.floor( Math.random() * upper ) + 1; }

This can help. Run the code a few times, and you will see how it works.

function getRandomNumber(upper) { 
  console.log("first just random---------------------");
  let num = Math.random();
  console.log(num);
  console.log("second random * upper---------------------");
  let numx = Math.floor( num * upper );
  console.log(numx);
  console.log("third random * upper + 1---------------------");
  console.log(numx + 1);
}

1 Answer

This function will give back a random number between 0 and the upper. So to break it down Math.floor(returns the largest integer less than or equal to a given number) and Math.random(returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1)) so if you won't more than 0 you do (* upper) bet than you don't get the max (you pick 9 max return = 8) so you do +1.

More info: → https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floorhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

I'm still kind of confused, i'm going to explain what i understand and you can correct me if im wrong. Upper is the given number we give it so lets say 10. How would that work out in this part of the code Math.floor( Math.random() * upper ) + 1; } . Math.random is a number between 0 and 1 but not 1 so lets say it comes out to 0.5 multiply that by the upper which i said was 10 that's 5. Then math.floor would return 5 since 5 is equal to 5. Then the plus 1 so the random number is 6 in my example here?

yes that should be correct