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

Harshay Raipancholi
seal-mask
.a{fill-rule:evenodd;}techdegree
Harshay Raipancholi
Python Development Techdegree Student 11,501 Points

Javascript 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
Grace Kelly
33,990 Points

I 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??

Harshay Raipancholi
seal-mask
.a{fill-rule:evenodd;}techdegree
Harshay Raipancholi
Python Development Techdegree Student 11,501 Points

Hi 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
Grace Kelly
33,990 Points

So in your code you are doing the following steps:

  1. Check the input the randomrange() function is receiving
  2. If either number is not a number then throw an error
  3. If not, return a random number from the input given

  4. 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 the alert() 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

if(isNaN(x) || isNaN(y) ) {

alert("Ooops, something went wrong!");
throw new Error("error not a number");

}