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

Infinite loop?

Although the code seems to be exactly the same as in the video, I never get the correct number and the prompt dialog box keeps popping up. It looks like an infinite loop. Did anyone managed to fix it?

                     var randomNumber = getRandomNumber(10);
              var guess;
              var guessCount = 0;
              var correctGuess = false;

    function getRandomNumber (upper) {

           var num = Math.floor(Math.random() * upper) +1;
           return num;
                }

    do {

              guess = prompt("I am thinking of a number between 1 and 10. Take a guess!")
          guessCount +=1;

            if(parseInt(guess) === randomNumber) {
                correctGuess = true; }


                           } while (! correctGuess) 

    alert("You guessed the number! It took you " + guessCount + " times to guess")

4 Answers

I just ran my code into the console and I understand what I was doing wrong. Since the initial number didn't change, by typing the same number all the time I was actually comparing the same two numbers, that's why I was never guessing the random one :-). Thx.

Just a spacing issue, you can't have the space between the ! and correctGuess.

(!correctGuess) 

@ Erik Nuber It's not working. I still have an infinite loop :(. Did you try running the code and it worked?

Actually it appears you don't even need to worry about the spacing. It worked as you have it written.

Yes, you just need to change the space between as above. It is the

while(!correctGuess)

I tried it in the console and it worked fine making that change.

I deleted that space and I changed the upper parameter to 2 so I limit the number of possibilities. I still can't seem to guess the number (the dialog box keeps coming back). And I can't access the console either since I can't get rid of the pop up message in any way.

try it this way...

1) copy your code 2) hit cmd + option + j to open the console 3) paste in your code and run it

I simply typed 1, 2, 3, 4...etc until I got the right answser. It worked fine.