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

Jonathan Leon
Jonathan Leon
18,813 Points

I think my loop is same as his but shorter, any thoughts?

do { 

  guess = prompt("IM THINKING OF A NUMBER BETWEEN 1 TO 10, WHAT IS IT?");
  guessCount +=1;


} while (parseInt(guess) != randomNumber )

  document.write("Correct,the number was " + randomNumber + " It took you " + guessCount + " attempts to guess the number.");

Looks good, Jonathan!

Seth Reece
Seth Reece
32,867 Points

I did mine completely different by writing to the document inside the if statement, then calling break; e.g.

do {
  guess = prompt("I'm thinking of a numnber between 1 and 10. What is it?");
  guessCount += 1;
  if (parseInt(guess) == randomNumber) {
    document.write("<p>Congradulations! You go it in " + guessCount + " tries!</p><p>The number was " + randomNumber + "!</p>");
    break;
  }
} while ( guess !== randomNumber )
Roman Rodionov
Roman Rodionov
6,810 Points

My syntax shorter too :)

var upper = 10;
var tries = 0;
var prog = program(upper);
function program(upper) {
  return Math.floor(Math.random() * upper) + 1;
}

do {
  var message = prompt('Try to guess the number!');
  tries += 1;
} while(parseInt(message) !== prog);

document.write('Got it in ' + tries + ' time!');

Hi Jonathan Leon, just letting you know I added code formatting/syntax highlighting.

1 Answer

Yes, your code also works! Note that as mentioned in previous videos/courses, you should do a strict equality/inequality check:

} while (parseInt(guess) !== randomNumber)

Technically you could shorten the loop even further, though I wouldn't recommend using this syntax:

do
  guessCount++;
while (parseInt(prompt("IM THINKING OF A NUMBER BETWEEN 1 TO 10, WHAT IS IT?")) !== randomNumber)

You could even have that on one line, to make it shorter, but even harder to read and understand! :)