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

Possible with this code?

Hi guys, I don't understand the logic of the "do.. while loop". I mean.. Could it be possible to use this code?

do { guess = prompt('I am thinking of a number between 1 and 10. What is it?'); guessCount +=1; }

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

Thanks for the answers! Luca

3 Answers

Has a few bugs. Try this:

var secretNumber = Math.floor(Math.random() * 10 + 1);
var guessCount = 0;
do {
    guess = prompt('I am thinking of a number between 1 and 10. What is it?');  
    guessCount +=1;
} while ( parseInt(guess) !== secretNumber);
alert("You guessed the secret number " + secretNumber + " in " + guessCount + " tries.");

First, get a random number between 1 and 10. Not sure what your randomnumber is, but it's undeclared and un-initialized.

Second, declare a variable to use to count up the user's guesses.

Third, modify the condition of the loop so that it runs until the user enters the secret number.

Note that there's a difference between !parseInt(guess) === secretNumber and parseInt(guess) !== secretNumber The former tries to apply the unary ! operator to an int, which won't fly. The latter says the guess isn't equal to the secret number.

Finally, you use a guessCount variable, but you don't initialize it or use it. So I put it to use in the last line of code.

j, as always apothegmatic.

Uhm... I lost something!!! Where do you declare the variable secretNumber?

So it's possible to use this code instead of the one shown in the video? The result is the same?

secretNumber is declared in this line:

var secretNumber = Math.floor(Math.random() * 10 + 1);

Re the video. Yes, it works the same.