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 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).
Syntax
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.
Note
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.
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 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 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
Leave a Review