Writing a While Statement

While is the most basic loop in Javascript, the most common one. While loop will always executed as long ad the condition is still met. For example :

var a = 0;

while (a < 10)
{
    alert(a);
}

Code above will make infinite loop, because every time they loop, the condition always met, 'a' is always will be less than 10 unless you changed it. That's why in every loop, we need something to change the value so it will exit when it finished.

var a = 0;

while (a < 10)
{
    alert(a);

    //increment a
    a += 1
}

The increment must be inside the loop itself. So with every loop, we will add 1 to variable 'a'. After ten loop, 'a' will be equal with 10, and the condition is no longer met.

results matching ""

    No results matching ""