Table of Contents

    JavaScript While Loop

    JavaScript While Loop

    JavaScript While Loop is used to execute a block of code for a number of times based on a condition.

    In this tutorial, we will learn how to define/write a JavaScript While loop, and its usage using example programs.

    Syntax

    The syntax of JavaScript While Loop is

    
    while (condition) {
         //statements
     }
    

    where condition is the expression which is checked before executing the statements inside while loop.

    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 While Loop.

    
    <!DOCTYPE html>
    <html lang="en">
    <body>
        <pre id="output"></pre>
        <script>
            var i = 0;
            while (i < 10) {
                document.getElementById('output').innerHTML += 'hello world\n';
                i++;
            }
        </script>
    </body>
    </html>
    

    Output:


    We can also use a while to iterate over the elements of an array, using array length in condition, as shown in the following example.

    
    <!DOCTYPE html>
    <html lang="en">
    <body>
        <pre id="output"></pre>
        <script>
            var arr = [10, 20, 30, 40];
            var i = 0;
            while (i < arr.length) {
                document.getElementById('output').innerHTML += arr[i] + '\n';
                i++;
            }
        </script>
    </body>
    </html>
    

    Output: