JavaScript JavaScript Numbers The Math Object Random Number Challenge – Two Numbers Solution

If 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
Tobias Edwards
14,455 Points

The 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.

Thanks Tobias i haven't looked into try-catch as of yet, but will make a note.