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

mrx3
mrx3
8,742 Points

My solution to the last javascript code challenge: Random number.

function getRandomNumber( lower, upper ) {
    if( isNaN(lower) || isNaN(upper)){
        // throw new Error("Both arguments must be numbers");
        return "Must be a number eg 9 not a string eg nine"
    }
  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 ) );

Is it okay that I used a string in a return statement? Could you explain why, or why not please?

2 Answers

Erik Nuber
Erik Nuber
20,629 Points

Yes, there is nothing wrong with returning a string. As you progress thru the courses, you might find that in some situations doing a build up of a statement is cleaner to do in a function and then return that statement.

mrx3
mrx3
8,742 Points

Erik, I kid you not...I spent at least 2 hours on this challenge. I knew about isNaN, and the ||, I didn't think the throw new Error was actually something you could use in javascript. I went to MDN and read about isNaN a bit, and thought maybe you could use a return statement, and BAMN!!! it worked. This is the first challenge I completed without looking at the solution video, so I'm pumped up :D Thank you for the reply.

Erik Nuber
Erik Nuber
20,629 Points

Congrats on doing that. I know how wonderful that feels. You also did what you will find yourself doing a lot and looking at the documentation. Somethings will start to feel second nature and you will just do them but, when you can't remember something, or have an idea for something you end up looking things up. That's natural. Congrats again!!!