Iterate with JavaScript Do…While Loops

Posted by

Iterate with JavaScript Do…While Loops

Do…While loops are a type of loop used in JavaScript to execute a statement or block of code until a given condition is met. This loop differs from the while loop in that it executes at least once regardless of the condition.

Syntax

The syntax for a Do…While loop is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

do {
    // code block to be executed
} 
while (condition);

[/dm_code_snippet]

The code block is executed first, then the condition is checked. If the condition is true, the code block is executed again. This process repeats until the condition is false.

Example

Let’s look at an example of a Do…While loop that prints out the numbers from 0 to 9:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var count = 0;

do {
    console.log(count);
    count++;
} 
while (count < 10);

[/dm_code_snippet]

Here, the code block is executed first and the count is set to 0. The console.log(count) statement prints out the current value of count, which is 0. The count is then incremented by 1. The condition is checked and since count is still less than 10, the code block is executed again. This process repeats until the condition is false.

Conclusion

Do…While loops are a useful type of loop in JavaScript that can be used to execute a statement or block of code until a given condition is met. The code block is executed at least once regardless of the condition.