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

Henning Holm
Henning Holm
4,163 Points

Better than while?

Any argument why rather use "do while" instead of this:

        while (!correctGuess){
        guess = prompt("Guess a number between 1 and 10!");
        guessCount++;
        if(parseInt(guess)===randomNumber){
            correctGuess=true;
        }
    }

2 Answers

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hi Henning,

As a while loop will only execute if the condition is met, how do you know if the guess is correct or not before the person has a chance to guess? If the user hasn't guessed yet (as the loop can't run the code block), then the loop doesn't know if !correctGuess is true of false.

A do/while loop will always execute at least once, regardless of the condition. This way, the code executes, the user guesses, the guess is checked... then the loop checks the condition to see if it will run again.

So, a do/while is more logical, more clear, and more safe as you don't need to hard-code an initial value for correctGuess in order for the loop to run.

Keep Coding! :) :dizzy:

Oussama Moulana
Oussama Moulana
2,977 Points

I get it the difference between While and Do While loop but the thing is the exercise in this video work if we use While. Maybe it should be more appropriate to do an example with an exercise which work only with a Do While loop?