Do-while loop code

Using do-while loop in javascript?
Difference between while and do-while?

Explanation

'do-while' loop is similar to while loop and the only difference here is that the set of statements are executed first and the condition is checked next.
Syntax:
do
{
// set of statements that will be executed
}
while(condition)

Here the statements are added under do loop and while condition is checked at the end of loop. In 'Do While' the statements are executed once even if the condition will fail.
An example

Example:


<script language="javascript">
var i=0;
do
{
document.write("Testing DO-While loop");
}
while(i!=0)
</script>

Result:



In the example the condition is 'i' should not be equal to zero. The statements are executed and the condition is checked. The condition failed. The pointer comes out of the loop. So the statements are executed once even when the condition fails.

Ask Questions

Ask Question