Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops `do ... while` Loops

Shahe Alam
Shahe Alam
1,500 Points

I don't understand "do while loop", I'm confuse

Would you explain in another way please.

1 Answer

Hey Shahe, I think you're going to be relieved when you realize how simple this really is once you get it. Here's the break down:

A while loop first checks to see if a specified condition is true, and if it is, then runs a bock of code. I.e.,

While (true) { console.log('hello world!') }

First the loop checks for the truth of the condition, then executes the code bock (obviously the above loop is an infinite loop and will run forever--and crash your browser!).

A do-while loop works similarly but in the reverse order. A do-while loop first executes a block of code, and then checks if a specified condition is true to see if it should execute that code block again. I.e.,

do { i = 0; console.log('hello world!'); i++; } while (i < 10);

In the do-while loop above, the block of code will run at least once before checking if the while condition is true. Even if i were equal to 10 right at the start, the code block would still run, but would not run again since the while condition would be false.

So summarize:

  1. While loops first check the while condition, and if it is true, run the code block.

  2. Do-while loops first execute code block, then check the while condition to see if they should run the code block again.

I hope this helps!