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) Making Decisions with Conditional Statements Build a Random Number Guessing Game

Christopher Johnson
Christopher Johnson
12,829 Points

What would you add in the else statement to rerun the if statement with another call to guess?

I feel like there is something simple to be added in the else statement to allow the user to guess indefinitely until he gets the answer correctly. I tooted around with it for a few minutes, but I decided to leave it as a question and move on.

3 Answers

Hope this helps!

var random = Math.floor(Math.random() * 4) + 1;

function guessFunction() {
  var guess = prompt("Guess between 1 and 4!");
  if (guess == random) {
    alert("Correct!");
  } else {
    alert("Try again!");
    guessFunction(); 
  }
};

guessFunction();
Wout Ceulemans
Wout Ceulemans
17,603 Points

If the prompt would open on load, then you could add 'location.reload()' in the else code block. This would reload the current document and therefor reopen the prompt to try again. But, there are obvious better ways of doing this. Such as using a loop or a function, but these concepts are probably out of scope if you are following the JavaScript Basics course.

You may want to include a sample of the code you are trying to run. The wording of your question is a little ambiguous. We all want to help, but I am not sure where you are going with this question.