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 trialSeokhyun Wie
Full Stack JavaScript Techdegree Graduate 21,606 PointsUsing '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
4,989 PointsThese 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
231,271 PointsAdding 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.
Seokhyun Wie
Full Stack JavaScript Techdegree Graduate 21,606 PointsSeokhyun Wie
Full Stack JavaScript Techdegree Graduate 21,606 PointsThansk Dmistry, I just checked it works the same. However I wonder what would be the mere difference there. :)