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 trialShahe Alam
1,500 PointsI don't understand "do while loop", I'm confuse
Would you explain in another way please.
1 Answer
Michael Cook
Full Stack JavaScript Techdegree Graduate 28,975 PointsHey 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:
While loops first check the while condition, and if it is true, run the code block.
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!