JavaScript Do-While Loop
JavaScript Do-While Loop is used to execute a block of code for one or more number of times based on a condition.
The basic difference between while and do-while loop is that, in while loop the condition is checked before execution of block, but in do-while the condition is checked after executing the block. Because of this, the code inside the loop is executed at least one in a do-while loop.
In this tutorial, we will learn how to define/write a JavaScript Do-While loop, and its usage using example programs.
Syntax
The syntax of JavaScript Do-While Loop is
do {
//statements
} while (condition);
where condition is the expression which is checked after executing the statements inside the loop.
do and while are keywords.
Examples
In the following example, we execute a block of code that appends ‘hello world’ to a pre block HTML element ten times using a Do-While Loop.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var i = 0;
do {
document.getElementById('output').innerHTML += 'hello world\n';
i++;
} while (i < 10);
</script>
</body>
</html>
Even if the condition is false for the first time, the code inside loop will be executed at least once.
Conclusion
In this JavaScript Tutorial, we learned about Do-While Loop, its syntax, and usage with examples.