Why use a "do while" loop?

Stanni picture Stanni · Jun 9, 2010 · Viewed 32.6k times · Source

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.

Answer

bakkal picture bakkal · Jun 9, 2010
  • As you see you had to repeat the same line in the second example. When you maintain, you most likely want those two lines to be the same, but you have repeated yourself.

  • Now Imagine that was a big block and not a line, not only will it take unnecessary precious visual space, but it will also be harder to maintain and attract inconsistencies.