Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.

David Thrower
David Thrower
6,693 Points

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.