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 trialja5on
10,338 PointsIf statement really needed?
I don't understand why if statement is needed.. i can get random number. Maybe the task was to include it but why is it needed and can another way be found? i like alternatives too.
2 Answers
Tobias Edwards
14,458 PointsThe if-statement is needed to check the type of what was inputted via the prompt()
, and then to display the appropriate message:
if (user entered a number) {
// do this
} else {
// display error message
}
Alternative method:
Use a try-catch. Assume the user entered a number and do stuff within the try
block, if an error is thrown (because the user didn't enter a number e.g. butter
) then catch it:
try {
// do something
} catch (error) {
// display error message
}
But I like the simple if-else statement in this case.
ja5on
10,338 PointsThanks Tobias i haven't looked into try-catch as of yet, but will make a note.