Table of Contents

    Mastering the JavaScript Do-While Loop: A Comprehensive Guide

    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.

    
    <!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>
    

    Output:


    Even if the condition is false for the first time, the code inside loop will be executed at least once.