totn JavaScript

JavaScript: Do-While Loop

This JavaScript tutorial explains how to use the do-while loop with syntax and examples.

Description

In JavaScript, you use a do-while loop when you are not sure how many times you will execute the loop body and the loop body needs to execute at least once (as the condition to terminate the loop is tested at the end of the loop).

Syntax

The syntax for the do-while loop in JavaScript is:

do {
   // statements
} while (condition);

Parameters or Arguments

condition
The condition is tested each pass through the loop. If condition evaluates to TRUE, the loop body is executed. If condition evaluates to FALSE, the loop is terminated.
statements
The statements of code to execute each pass through the loop.

Note

  • You would use a do-while loop statement when you are unsure of how many times you want the loop body to execute.
  • Since the while condition is evaluated at the end of the loop, the loop body will execute at least once.
  • See also the break statement to exit from the do-while loop early.
  • See also the continue statement to restart the do-while loop from the beginning.

Example

Let's look at an example that shows how to use a do-while loop in JavaScript.

For example:

var counter = 1;

do {
   console.log(counter + ' - Inside do-while loop on TechOnTheNet.com');
   counter++;
} while (counter <= 5)

console.log(counter + ' - Done do-while loop on TechOnTheNet.com');

In this do-while loop example, the loop would terminate once the counter exceeded 5 as specified by:

while (counter <= 5)

The do-while loop will continue while counter <= 5. And once counter is > 5, the loop will terminate.

In this example, the following will be output to the web browser console log:

1 - Inside do-while loop on TechOnTheNet.com
2 - Inside do-while loop on TechOnTheNet.com
3 - Inside do-while loop on TechOnTheNet.com
4 - Inside do-while loop on TechOnTheNet.com
5 - Inside do-while loop on TechOnTheNet.com
6 - Done do-while loop on TechOnTheNet.com