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

Marko Delgadillo
Marko Delgadillo
4,524 Points

Why is my code immediately printing the error message and not numbers first?

function getRandomNumber( lower, upper ) { if (isNaN(lower) || isNaN(upper)) { //isNan is used to determine if a value is NOT a number throw new Error('HEY! I said a number!'); //This method can help debug code

} else {

return Math.floor(Math.random() * (upper - lower + 1)) + lower; } } console.log( getRandomNumber( 1, 124 ) ); console.log( getRandomNumber( 4, 24 ) ); console.log( getRandomNumber( 200, 'five hundred' ) ); console.log( getRandomNumber( 1000, 20000 ) ); console.log( getRandomNumber( 50, 100 ) );

Why is this code immediately printing my error message instead of a number between 1 and 124 AND 4 and 24??? It should print the error message on the third console.log.

2 Answers

Steven Parker
Steven Parker
231,248 Points

Perhaps it's your browser.

I get exactly what you expect, two numbers and then the error. But perhaps your browser doesn't show any output until the program stops.

I'm using Chrome, what about you?

Hey, maybe I can help... I got that too. It's completely normal. If you remember that in the video, Dave has a number instead of a string as his first argument, but the workspace we've been given to work on has a string as the first argument. That's why the error message is thrown as soon as the error is detected. We were busy working on the challenge that we forgot what was in the console.log.

I missed that too.