JavaScript WHILE loops

This page is marked as In Progress so expect small errors or unfinished bits

JavaScript FOR loops run a set number of times. Sometimes you don't know how many iterations are needed before you want to stop. WHILE loops can handle this:

while (positionx!=0) {                
        

The code in the braces will run over and over until positionx equals zero. For this to happen something inside the loop would have to change positionx so that it will at some point be zero. If it never equals zero the loop will run forever and your page will freeze up. If positionx starts off as zero then the code will never run. Be careful with WHILE loops.

There is also a similar loop which will always run once because it does the check at the end - after the code has run once:

do {
    // some code goes here
while (positionx!=0);
        

You may never use that as most things can be done with a WHILE loop.

submit to reddit Delicious Tweet