# Loops Kevin Harville for loops for my Var

• Slides: 12

Loops Kevin Harville

for loops for (my. Var = 1; my. Var<=10; my. Var + 2){ alert(my. Var) } ® Loop, through the braced code starting with my. Var at 1. ® Continue as long as my. Var 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 =" "); document. write(document[i]); }

Loops and Arrays ® Loops are very often used with arrays. ® Remember, arrays are objects that consist of several subscripted variables: my. Array = new Array(); my. Array[0] = 24 my. Array[1]= 12 my. Array[2] = 4

Looping through an Array for (i=0; i <= 2; i++) { alert(my. Array[i]) }

Putting it all together: my. Array = new Array(); my. Array[0] = 24 my. Array[1]= 12 my. Array[2] = 4 for (i=0; i <= 2; i++) { alert(my. Array[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