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

Hunter Shaw
Hunter Shaw
2,187 Points

I'm not sure why my code doesn't work, help?

I'm not really sure how the isNaN works. I'm almost positive this has to do with my program not working.

function getRandomNumber( lower, upper ) {
  var random = Math.floor(Math.random() * (upper - lower + 1)) + lower; 
  if (isNaN(lower) || isNaN(upper)) {
    throw new Error("Error, please provide a number...");
  } else 
    return random;
}

document.write( getRandomNumber( 'nine', 24 ) + "<br>");
document.write( getRandomNumber( 1, 100 ) + "<br>");
document.write( getRandomNumber( 200, 'five hundred' ) + "<br>");
document.write( getRandomNumber( 1000, 20000 ) + "<br>");
document.write( getRandomNumber( 50, 100 ) + "<br>");
Antonio De Rose
Antonio De Rose
20,885 Points

please do the sanity check before doing the calculation

I do not know, why you say the code does not work, it does work for me, the program stops at the first instance, as that itself brings in an error, as put by you if you want to see a change, change the order

document.write( getRandomNumber( 1, 100 ) + "<br>");
document.write( getRandomNumber( 'nine', 24 ) + "<br>");
document.write( getRandomNumber( 200, 'five hundred' ) + "<br>");
document.write( getRandomNumber( 1000, 20000 ) + "<br>");
document.write( getRandomNumber( 50, 100 ) + "<br>");

1 Answer

Steven Parker
Steven Parker
231,269 Points

The code seems to work fine. :+1: But since errors are being deliberately generated, you can only see the results in the JavaScript console.

If you wanted to see them on the page instead, you could replace "throw new Error" with "return".