Do-while statement

Possible duplicate:
When is it suitable?

Could someone tell me what is the difference between these two statements and when to use each other?

var counterOne = -1; do { counterOne++; document.write(counterOne); } while(counterOne < 10); 

and

 var counterTwo = -1; while(counterTwo < 10) { counterTwo++; document.write(counterTwo); } 

http://fiddle.jshell.net/Shaz/g6JS4/

At this point in time, I do not see the point of the do statement if this can be done without specifying it inside the while statement.

+7
source share
6 answers

Do / While VS. While the condition is checked.

A while loop checks the condition and then executes the loop. A Do / While runs a loop and then checks the conditions.

For example, if the counterTwo variable was 10 or more, then the / while loop ran once, while your regular while loop did not run the loop.

+20
source

It is guaranteed that do-while works at least once. Although the while may not work at all.

+8
source

The do statement usually guarantees that your code will be executed at least once (the expression is evaluated at the end), while it is evaluated at the beginning.

+1
source

Suppose you want to process a block inside a loop at least once, regardless of the condition.

+1
source

do while checks conditional state after block start. while checks the conditional expression before running it. This is usually used in situations where the code always runs at least once.

+1
source

if you get the value of counterTwo as the return value of another function, in the first case you have to make sure that the if statement.

eg.

 var counterTwo = something.length; while(counterTwo > 0) { counterTwo--; document.write(something.get(counterTwo)); } 

or

 var counterTwo = something.length; if(counterTwo < 0) return; do { counterTwo--; document.write(something.get(counterTwo)); } while(counterTwo > 0); 

The first case is useful if you are processing data in an existing array. The second case is useful if you are "collecting" data:

 do { a = getdata(); list.push(a); } while(a != "i'm the last item"); 
+1
source

All Articles