Robin D.
Robin D.

Reputation: 97

Javascript Guessing Game - Counter Not Working

I am trying to create a Javascript guessing game where the user has 10 tries to guess a number between 1-999. I have to use a validate the number, use a loop and show alerts if the user gets a match and also when they run out of guesses. Using the number 45 just for testing. Each guess should be numbered and displayed using innerHTML. Problem is, the counter is stuck at zero. Not sure what I'm missing! Code below:

function myFunction() {
  var userInput = document.getElementById("input").value;
  var randomNum = 45;
  // test for valid input number from 1 to 999
  if (userInput < 0 || userInput > 999) {
    alert("Your number must be from 1 to 999");
  } else {
    alert("Input OK");
  }
  var counter = 0;
  while (counter < 10) {
    counter++;
    if (userInput == randomNum) {
      alert("You win!");
    }
    if (userInput > randomNum) {
      document.getElementById("loopResults").innerHTML += counter + "." + " Your answer: " + userInput + "." + " Guess lower! < br / > ";
      alert("You have " + counter + " guesses left.");
    } else if (userInput < randomNum) {
      document.getElementById("loopResults").innerHTML += counter + "." + " Your answer: " + userInput + "." + "Guess higher! < br / > ";
      alert("You have " + counter + " guesses left.");
    }
    break;
  } // end while loop
} // end function myFunction()

Upvotes: 1

Views: 676

Answers (3)

Steve Wakeford
Steve Wakeford

Reputation: 331

This line

var counter = 0;

resets counter to 0 every time the function is called. One fix could be to set this as a global variable in this way

counter = 0; // note no var keyword
function myFunction() {...}

Then your calls to counter in the function will reference the global variable.

In addition, your while loop doesn't make sense. It should be a simple if statement to see if counter >= 10. Think about this logic after counter variable is being set correctly.

Upvotes: 3

TimoStaudinger
TimoStaudinger

Reputation: 42460

Only break your loop when you actually want to exit it. In your case, that would probably be when the user has guessed the number or is out of tries.

The break command immediately ends the loop. Have a look at the MDN docs for more info!

Upvotes: 1

Anthony Chung
Anthony Chung

Reputation: 1477

Step through the logic in your while loop.

The counter variable incrementing in each loop will already cause your loop to exit.

Setting a "break" at the end of the while loop means that you are guaranteed to exit after the first

Upvotes: 1

Related Questions