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

My solution

function getRandomNumber( lower, upper ) {
  var randomNumber = Math.floor(Math.random(lower) * (upper)) + 1; 
  return randomNumber
}

alert( getRandomNumber(100,10) );
alert( getRandomNumber(0,6) );
alert( getRandomNumber(9,78) );

Did you have a question? Or were you looking for critique?

2 Answers

No no question. Just would like some feedback.

So it looks like your function is supposed to return a random integer between [lower] and [upper], correct?

if so, here a couple of pieces of feedback:

First, Math.random() doesn't take any parameters, so you don't want to try and pass [lower] into it.

Math.random() returns a random value between 0 and 1, so you want to multiply that number by the range between your lower and upper. So say you want a number between 1 and 3...the range is 2, so you are going to multiply that by the random number from Math.random. To do this, you use this formula:

Math.random() * (upper - lower);

so if upper = 3, and lower = 1, this would return a number between 0 and 2. Then you would just add [lower] to that to get a number within the range you want...1-3 in this case

Math.random() * (upper - lower) + lower;

again, if upper = 3, and lower = 1, this would return a random number between 1 and 3. Then you round down to get the random integer, just like you had...

Math.floor(Math.random() * (upper - lower) + lower;);

Next, and this isn't a requirement, but just so you can see it and save yourself a line of code, you can actually return this entire equation without first having to store it in a variable...like this:

return Math.floor(Math.random() * (upper - lower) + lower;);

So the entire function would look like this:

function getRandomNumber( lower, upper ) {
  return Math.floor(Math.random() * (upper - lower) + lower;);
}

Finally, the first time you call the function in your example, you give a larger number first (100), and then a smaller number (10). This is going to yield different results than you are wanting. In this case you would end up getting a random number between -80 and 10, so just be mindful of that.

I know this is a lot, but I hope it helps!