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, Part II Solution

Juan García
Juan García
10,723 Points

I made it more fun having the user choose the lower and higher number

function randomNumber ( lower, higher ) {
  if ( isNaN(lower) || isNaN(higher) ) {
    throw new Error('That is not a number');
  } 
  var result = Math.floor(Math.random() * (higher - lower + 1) + lower); 
  return result;
}

var lowerNumber = parseInt(prompt('Choose the lower number.'));
var higherNumber = parseInt(prompt('Choose the higher number'));


document.write('<p>Your random number is ' + randomNumber(lowerNumber, higherNumber) + '.</p>');

It was a headache when I forgot to use parseInt() with the answer provided by the user in prompt().

Also, throw new Error( doesn't seem to do anything on firefox)

Well done, Juan García! throw new Error() works the same in Firefox as it does in Google Chrome. It prevents the execution of the rest of the function and throws whatever string you've placed into the Error() portion out to the console. If you take a look at Firefox's web console, you'll see the error being thrown.

Howie Yeo
Howie Yeo
Courses Plus Student 3,639 Points

Thank you Juan García! I was cracking my head on how to generate random number using user input + arguments! This really solve my problem :D