Alex Rivera | Logout

Why use a "do while" loop?

Asked 2010-06-09T06:14:13.883
16

I've never understood why using a do while loops is necessary. I understand what they do, Which is to execute the code that the while loop contains without checking if the condition is true first.

But isn't the below code:

do{
    document.write("ok");
}
while(x == "10");

The exact same as:

document.write("ok");
while(x == "10"){
    document.write("ok");
}

Maybe I'm being very stupid and missing something obvious out but I don't see the benefit of using do while over my above example.

Edit
Report

1 Answer

1

First of all your do..while syntax is wrong. It is like this:

do
{
  document.write("ok");
}while(x=="10");

It is useful when you want to execute the body of the loop at least once without evaluating its teminating condition. For example, lets say you want to write a loop where you are prompting the user for input and depending on input execute some code. You would want this to execute at least once and then ask the user whether he wants continue. In such cases, do..while loop results in lesser and cleaner code compared to a while loop.

answered 2010-06-09T06:21:51.940

Your Answer