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


Tomas Rinblad
Tomas Rinblad
Full Stack JavaScript Techdegree Student 12,427 Points

Why is my code in JavaScript looping endless? - Solved

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

function computer () { var guess = getRandomNumber(10); return guess; }

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. What is it?"); guessCount += 1; if (parseInt(guess) === randomNumber){ correctGuess = true; } } while (! correctGuess )

do { computer (); computerCount += 1; if ( parseInt( computer ) === randomNumber) { computerGuess = true; } } while (! computerGuess)

document.write("<h1>You guessed the number!</h1>");
  document.write("<p> It took you " + guessCount + " times to find the correct number!</p>");
    document.write("<p> And it took the computer " + computerCount + " tries</p>");

I am trying to make the code first make you as an user guess the number. When you have guessed and gotten the correct answer the computer does the same thing. But it seems that this code are doing an endless loop (chrome crashing all the time). I am not totaly sure why this is happening (crashing/looping) anyone that can see the fault?

2 Answers

Steven Parker
Steven Parker
229,657 Points

You're treating a function like a string.

For the computer turn, you call the computer() function but you don't store the return value anywhere. Then, you attempt to convert the function itself into an integer and compare it with the chosen number. This will always fail and so the loop repeats forever.

You can correct and simplify the computer turn a bit by calling the computer() function directly in the test since it the number it picks does not need conversion.

do {
  computerCount += 1;
  if (computer() === randomNumber) {
    computerGuess = true;
} while (!computerGuess);

You could also simplify it a bit more by performing the test directly in the while expression:

do {
  computerCount += 1;
} while (computer() != randomNumber);