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

Seokhyun Wie
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Seokhyun Wie
Full Stack JavaScript Techdegree Graduate 21,606 Points

Using 'else' clause instead of directly writing 'return' clause

Hi guys, I used a little bit of different approach from the solution that is mentioned in the video.

function randomNumber(lower, upper) {
    if (isNaN(lower) || isNaN(upper)) {
        throw new Error('error message');
    } else {
        return Math.floor(Math.random() * (upper - lower + 1) + lower);
    }
}
console.log(randomNumber('nine', 1000));

Is there any problem with this approach? If there is, please let me know, or if not, also please let me know the pros and cons of it. Thank you so much!

2 Answers

Dmitry Polyakov
Dmitry Polyakov
4,989 Points

These two functions will produce the same result

function randomNumber(lower, upper) {

if (isNaN(lower) || isNaN(upper)) {

    throw new Error('error message');

} else {

    return Math.floor(Math.random() * (upper - lower + 1) + lower);

}

}

console.log(randomNumber('nine', 1000));

function randomNumber(lower, upper) {

if (isNaN(lower) || isNaN(upper)) {

    throw new Error('error message');

} 

 return Math.floor(Math.random() * (upper - lower + 1) + lower);

}

console.log(randomNumber('nine', 1000));

Steven Parker
Steven Parker
231,269 Points

Adding the "else" won't cause any difference in behavior; but it's not needed, since when the "if" test is true, the "throw" will stop the function. So any code after the conditional block can only run in the "else" condition.