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 trialJoel Pendleton
19,230 PointsMy Response
function randomNum(num1, num2) {
if (isNaN(num1) || isNaN(num2)) {
throw new Error('Please enter a number.');
} else {
return Math.floor(Math.random() * (num1 - num2 + 1)) + num2;
}
}
The else conditional statement ensures that a random number will only be generated if both num1 and num2 are numbers. There's no need for this else statement if an error is thrown before it. This is because, the program wouldn't run the following lines of code after the error (because the program ends). However, you should add the else condition if there is no error message being thrown to ensure that your random number generator is only run under your wanted conditions - num1 and num2 being numbers and not strings.
1 Answer
Iain Simmons
Treehouse Moderator 32,305 PointsYou're correct, the else
isn't needed, but you've also done something that many programmers recommend, which is to be explicit. That is, making it clear that the return
statement should only be run if the parameters are integers.