Loops Kevin Harville
for loops Loop, through the braced code starting with myVar at 1. for (myVar = 1; myVar<=10; myVar + 2){ alert(myVar) } Loop, through the braced code starting with myVar at 1. Continue as long as myVar is <= 10 Increment by 2
while loops while (condition == true){ alert("True"); //maybe the condition changes } While loops repeat as long as the condition remains true.
while loops //previous statements … while (condition == true){ alert("True"); } //subsequent statements… The loop would be passed over if the condition were never true--Just like an if statement.
do while loops do { alert("True") //maybe the condition changes } while (condition == true); When the program reaches this point, the loop would execute at least once. The condition is at the end of the loop.
Breaking out while (condition == true){ alert("True"); if (tired == true) break; } //subsequent lines While loops repeat as long as the condition remains true….unless we break out of the loop. For loops repeat their iterations* as scheduled until a break is reached. *Iteration: Geekspeak for times.
continue var x = 5; while (x < 10) { x++; if (x == 7) continue; document.write(x + "<BR>"); } Continue continues on with the next iteration of the loop.
for … in loops Similar to the previous but cycle through all properties of an object. Know they exist. They are handy, particularly for debugging. for (i in document) { document.write("<p>" + i ="<br>"); document.write(document[i]); }
Loops and Arrays Loops are very often used with arrays. Remember, arrays are objects that consist of several subscripted variables: myArray = new Array(); myArray[0] = 24 myArray[1]= 12 myArray[2] = 4
Looping through an Array for (i=0; i <= 2; i++) { alert(myArray[i]) }
Putting it all together: myArray = new Array(); myArray[0] = 24 myArray[1]= 12 myArray[2] = 4 for (i=0; i <= 2; i++) { alert(myArray[i]) }
Summary of Loops for loop while loop do / while loop for / in loop for use with object properties break finishes the loop altogether continue goes directly to the next iteration Much can be accomplished with arrays and loops