JavaScript Loops
For Loop:
for (var counter = 0; counter < 21; counter++) { //--Code block to be executed--//Each for loop must be given three statements, separated by semicolons, in a set of parenthesis following the decalaration. Think of these as the instructions you are giving JavaScript to run your loop.
The first statement establishes the start position ("0") for the loop, the second establishes a condition that must be met for the loop to run an iteration (here counter must equal a number less than "21"), and the last specifies the increment as advancement. In this case ("counter++"), the "counter" varaible is incremented by 1. With the for loop, the variable is incremented after an interation is run.
Incrementing by 1 can take the form of "i++" for a variable named "i" ; Decrementing i can be done by "i--" ; Incrementimng or decrementing by some other number besides 1 can be done by "i += x" or "i =- x" where is x is the number we want to increment or decrement by, respectively.
While Loop:
while(condition){ //--Code block to be executed--// }A While loop will continue to execute as long as the condition evaluates to 1 or true. A while loop can be set to run by declaring a variable that evaluates to true in the condition.
Note that the condition does not have to be explicitly stated. For instance:
var wind = true; while(wind === true){ //--Code block to be executed--// }...is the same as...
var wind = true; while(wind){ //--Code block to be executed--// }
Do While Loop:
do { //--Code block to be executed--// } while (condition);The do loop is similar to thw while loop except that it checks the condition after the loop is run once (rather than before).
function sampleForIn() { //The sample object// var MyObject = { width: "14", length: "12", depth: "34"} //The loop for (var iterate in MyObject) { document.writeln(iterate + ""); } document.writeln(MyObject.length); }
For...In Loop:
The For...In loop iterates through each property in an object, though not, somewhat annoyingly--always in order://The sample object// var MyObject = { width: "14", length: "12", depth: "34"} //In this loop, "iterate" is not a special keyword// //It is just a variable name I made up// for (var iterate in MyObject) { document.writeln(iterate + " = " + MyObject[iterate] +"<br>"); } document.writeln(MyObject.length); }...produces the output...
width = 14 length = 12 depth = 34...usually, but not always in that order. Also, don't use For...In to iterate over an array. Bad things could happen, the Web says.