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

Forever in a Do While Loop

var randomNumber = getRandomNumber(low, high);
var guess;
var guessCount = 0;
var correctGuess = false;
var low = 1;
var high = 10;

function getRandomNumber( lower, upper ) {
  var num = Math.floor(Math.random() * (upper - lower + 1)) + lower;
  return num;
}

do {
  guess = prompt('I am thinking of a number between ' + low + ' and ' + high + '. What is it?');
  guessCount += 1;
  if (parseInt(guess) === randomNumber) {
    correctGuess = true;
  }
} while ( ! correctGuess )

document.write('<h1>You guessed the number!</h1');
document.write('It took you ' + guessCount + ' tries to guess the number ' + randomNumber + '.');

I cannot seem to get out of this loop and I don't know where I went wrong. Any help would be greatly appreciated.

1 Answer

Steven Parker
Steven Parker
243,656 Points

On the first line, you call the function "getRandomNumber" and pass it "low" and "high" as arguments. Because of "hoisting", the function and the variable names are accessible, but since the value assignments have not take place yet, both arguments have undefined values. The causes the function to generate a result that is not a number ("NaN").

The loop runs forever because nothing will match NaN.

The remedy is to just move the line that calls "getRandomNumber" down below the lines that assign the values for "low" and "high".