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!
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

shay r
11,337 PointsJavascript Function Problem - Help
Hello Treehouse community, Please can you help me with the code below, it should throw an error. But for some reason it doesnt work (it does not throw an error when it should)
function randomrange(x,y) {
if(isNaN(x) || isNaN(y) ) {
throw new Error("error not a number");
}
var randnum = Math.floor(Math.random() * (x - y + 1)) + y;
return randnum;
}
alert(randomrange("nine",6));
/*****************************************************************************/
2 Answers

Grace Kelly
33,990 PointsI ran your code in the developer console and i got the following:
alert(randomrange("nine",6));
VM724:5 Uncaught Error: error not a number
at randomrange (<anonymous>:5:7)
at <anonymous>:1:7
It's throwing the error, which would suggest that it does work :) unless it's something different you're trying to achieve??

shay r
11,337 PointsThanks!
shay r
11,337 Pointsshay r
11,337 PointsHi Grace,
Thanks for your response.
The error should appear in a alert box, because I'm using alert() , would the alert not appear In a alert box? is there a way to do this?
Thanks again, Shay
Grace Kelly
33,990 PointsGrace Kelly
33,990 PointsSo in your code you are doing the following steps:
randomrange()
function is receivingIf not, return a random number from the input given
Call the function inside an
alert()
alert(randomrange("nine",6));
Here you've provided the
randomrange()
function an invalid number "nine", it goes from step 1 to step 2. It sees the value is not a number so it throws an error and quits the function, therefore thealert()
doesn't get called because it got interrupted.The throw new Error logs the error out to the console which is the output i posted above is. You could place the alert inside the if statement aswell, so the error is thrown and the user is alerted e.g