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

Nicholas Woods
Nicholas Woods
6,260 Points

Throw new Error(); not showing error, but shows syntax error in console.

Cannot figure out what is going wrong here. Hope someone can enlighten me. The specific problem seems to be with the 'throw new Error();' function.

random.js
//
function randomNumber(upper, lower) {
  var randomNum = Math.floor(Math.random() * (upper - lower + 1)) + lower; 
  return randomNum;
}

// Getting the users numbers
var lowerNum = prompt("Pick a number");
var upperNum = prompt("Pick a larger number");
var int1 = parseInt(lowerNum);
var int2 = parseInt(upperNum);

// Checking they gave number digits
var num1 = isNaN(int1);
var num2 = isNaN(int2);

// throwing error if missing number digits
if ( num1 === true || num2 === true ) {
  throw new Error("You need to use number digits like 1 2 3");
}

document.write(randomNumber(int1, int2) + " is a random number between your choices.");
Nicholas Woods
Nicholas Woods
6,260 Points

I think I may have misunderstood what this function does. I wanted to let the user know they had not given me a usable number. Still not entirely sure how I would use 'throw new Error();', so any help would be appreciated.

2 Answers

Brandon Semilla
Brandon Semilla
4,858 Points

It doesn't look like your code has any problems. When I use non-number values, I get the desired error: "Uncaught Error: You need to use number digits like 1 2 3".

Here's a fiddle!

Nicholas Woods
Nicholas Woods
6,260 Points

Yea, I realised this after posting. Thanks.

should i be getting an alert box for this for error message? i am not only console function getRandomNumber( lower, upper ) { if ( isNaN(lower) || isNaN(upper) ) { throw new Error ('error message'); } else {return Math.floor(Math.random() * (upper - lower + 1)) + lower; } } console.log( getRandomNumber( 'nine', 24 ) ); console.log( getRandomNumber( 1, 100 ) ); console.log( getRandomNumber( 200, 'five hundred' ) ); console.log( getRandomNumber( 1000, 20000 ) ); console.log( getRandomNumber( 50, 100 ) );