Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics (Retired) Creating Reusable Code with Functions Random Number Challenge

Michael Lambert
Michael Lambert
6,286 Points

My solution to the quiz task

// generate random number
function randomNumber(upper, lower) {
  return Math.floor(Math.random() * (upper - lower + 1)) + lower;
}

// get inputs from user and display the result
function getNumbers() {
  var num1 = parseInt(prompt('Enter first number'));
  var num2 = parseInt(prompt('Enter second number'));
  var upperNum = Math.max(num1, num2);
  var lowerNum = Math.min(num1, num2);
  console.log(randomNumber(upperNum, lowerNum));
}

// run it 5 times
getNumbers();
getNumbers();
getNumbers();
getNumbers();
getNumbers();

I havn't checked it extensively but it seems to be working as expected. Is there anything i can do to streamline the code while maintaning the same functionality?

3 Answers

Peter Quin
Peter Quin
3,200 Points

Maybe you could add a for loop instead of the five calls:

for (i = 0; i < 5; i++) {
   getNumbers();
}

removes a few lines

Michael Lambert
Michael Lambert
6,286 Points

I haven't got that far in the course yet where they cover loops but it looks simple enough to understand so thanks for the introduction to using them :). I've implemented your code into it now and set it to 10. Saves a whole bunch of repeated code.

Michael Lambert
Michael Lambert
6,286 Points

I had considered using conditionals for checking min and max but i ended up trying out the Math.max & Math.min which i stumbled across earlier in the week but didn't have cause to use them at the time. Thanks for the example though :)

Tyler Corum
Tyler Corum
3,514 Points

At the end of your code, Shivang, you don't need to create a variable called numArgument, nothing is being returned anyway. Just call the function...

randomNumber(num1, num2);

Keep up the good work.

Tyler Corum
Tyler Corum
3,514 Points

Very readable, great job. I like your descriptive variable and function names!