Using Do-While Loop to coding in Javascript/JS

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


In JavaScript, you use a do-while loop when you are now not positive how many instances you will execute the loop physique and the loop physique wishes to execute at least as soon as (as the circumstance to terminate the loop is examined at the quit of the loop).


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

do {
   // statements
} while (condition);

Parameters or Arguments

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


You would use a do-while loop statement when you are not sure of how many instances you prefer the loop body to execute. Since the while situation is evaluated at the give up of the loop, the loop body will execute at least once. See additionally the break assertion to exit from the do-while loop early. See additionally the continue declaration to restart the do-while loop from the beginning.


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');
} while (counter <= 5)

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

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

while (counter <= 5)

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

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

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