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

Do vs While

Excuse my ignorance, but does it make more sense to use a Do loop when you can manipulate the arguments of a While loop via "!==" and "=="?

While thinking this out, I suppose in the case of a prompt a Do loop would make more sense. This way you would not have to specify the prompt outside of the While loop then once again inside the While loop?

I didn't notice your comment, Brandon, but you could do either loop without having to prompt twice:

The do-while loop:

var password;
do {
password = prompt("What is the password?");
} while (password !== "sesame")

And the while loop version:

var password;
while (password !== "sesame") {
password = prompt("What is the password?");
}

1 Answer

Hey Brandon Meredith,

Either way is perfectly valid. And you're not speeding up the program by switching over to a do...while method. This video is really just to teach you how the do...while loop works.

Which loop to use is really dependent on what you're trying to do. do...while loops will execute the body of the do statement and then check the while condition to see if it is still true and repeat that process if it is. As soon as the condition becomes false, the do loop will no longer execute. A while loop will check the conditional first, then execute the body of the loop and then will cycle over the block of code so long as the conditional remains true. So, really, it depends on whether you need the code to run first then check the conditional (do while loop) or check the conditional then run the code (while loop).

If you have a variable that exists perhaps in the global scope, and you don't want the code executing in the loop if the condition is false, you could just use the while loop. If you want to run some code and then check whether something in that block ends up making your condition false, you can run the do...while loop.