Javascript: While loop

This entry is part 16 of 27 in the series Javascript Tutorial

The while statement creates a loop that executes a specified statement as long as the test condition is true.

<!DOCTYPE html>
        function myFunction() {
            var n = 0;
            var x = 0;
            while (n < 3) {
                n = n+1;
                x = x+n;
                document.getElementById("id_n").innerHTML = n;
                document.getElementById("id_x").innerHTML = x;
<p id="id_n">n</p>
<p id="id_x">x</p>
<button onclick="myFunction()">Click Me</button>
Try The Code  

As n starts with 0 and the condition is (n < 3), while loop will run 3 times and the n will evaluate to 3 and x will evaluate to 1+2+3=6.


Series Navigation<< Javascript: If Else
Javascript: Array >>