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) Creating Reusable Code with Functions Random Number Challenge

Zankruti Murray
Zankruti Murray
8,969 Points

My Solution, is it correct?

Math.floor(Math.random() * (6 - 1 + 1)) + 1; 

function randomNum (maxNum, minNum) {
  var getRandomNum = Math.floor(Math.random() * (maxNum - minNum + minNum)) + 1; 
  return getRandomNum;
}
alert(randomNum(100, 10));
alert(randomNum(300, 100));

3 Answers

Grace Kelly
Grace Kelly
33,990 Points

Hi Zankruti, your solution looks all good from what I can see!! However if I could make one suggestion, it would be to rename your function and variables so that they explain better what they are doing, for example I would rename them to the following:

function getRandomNum (maxNum, minNum) {
  var randomNum = Math.floor(Math.random() * (maxNum - minNum + minNum)) + 1; 
  return randomNum;
}

alert(getRandomNum(100, 10));
alert(getRandomNum(300, 100));

I would call the function getRandomNum because it is getting the random number value, and I would call the returned variable randomNum because that is the random number value that the function returns...i hope that makes sense!!

I would do this because if anyone else was looking at your code or if you were referring to it in the future it can make things much clearer to read and understand :)

Zankruti Murray
Zankruti Murray
8,969 Points

Thank you Grace, I understand what you mean and will keep it in mind.

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,252 Points

"Is it correct?", can be a relative question.

If the answer to the following questions

  • Does the program do what it was intended to do, that is give a random number between a range of 2 numbers then yes the code is
  • Is the code free of bugs and syntax errors

...is yes then yes the code is correct. There are many ways to solve any programming problem. :-)

Zankruti Murray
Zankruti Murray
8,969 Points

Thank you Jonathan, Yes I should have framed my question more clearly.

Unfortunately, it's not quite right here...

The 'formula' should be Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum;

If you look at your original function, you're just adding and then immediately subtracting minNum within the parentheses.