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 JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops `do ... while` Loops

I keep on getting an endless loop, and whenever I launch my workspace it becomes unresponsive and treehouse webpage

var upper = 10; var attempts = 0; var message; var answer = parseInt(message); var correct = false;

function randomNumber(upper){ var rand = Math.floor(Math.random() * upper) + 1; return rand; }

do{ message = prompt("Guess my correct random number between 1 and 10"); attempts += 1; if(answer === randomNumber(upper)){ correct = true; } }while( ! correct )

document.write("<p>It took you " + attempts + " times before you got " + randomNumber(upper) + " correctly" + ".</p>");

Robert Howington
Robert Howington
1,787 Points

When you write message to document, you are again calling the randomNumber(), so if you do match during the game, the random value in your message won't actually be the value that was matched.

1 Answer

Robert Howington
Robert Howington
1,787 Points

I was able to get it to work by eliminating the global answer variable and just combining it in the Do/while loop. Also referenced the 'rand' variable on the .write() method params

var upper = 10;
var attempts = 0;
// var answer = parseInt(message); *** Moved into Do/while Loop *** //
var correct = false;
var rand;

function randomNumber(upper) {
  return rand = Math.floor(Math.random() * upper) + 1;
}

do {
  answer = parseInt(prompt("Guess my correct random number between 1 and 10"));
  attempts += 1;
  if (answer === randomNumber(upper)) {
    correct = true;
  }
}
while (!correct)
  document.write("<p>It took you " + attempts + " times before you got " + rand + " correctly" + ".</p>"); 

Thank you very much Robert, the code is up and running. With these little adjustments I now COMPLETELY understand what you were trying to explain in your previous reply. You can delete the message variable by the way :)