Another key concept across the board with programming language is the concept of loops. A loop is something that repeats over and over again. This repeat is known as an iteration. Loops repeatedly iterate until they finally terminate.
The loops in JavaScript are:
- While loops
- Do while loops
- For loops
- For-in loops
While loops
A while loop repeats while a condition is true.
var i = 0; while(i < 10) { alert(i); i++; }
This loop will almost act as an if statement and will not be run:
var i = 0; while(i > 10) { alert(i); i++; }
And this loop will run indefinitely (an infinite loop):
var i = 0; if (confirm("Are you sure you want to execute an infinite loop?")){ while(true) { alert(i); i++; } }
Running an infinite loop without terminating it may cause the user's browser to crash, or in the case above will keep showing a dialog box to the user.
Do while loops
A do while loops at least once and loops until a condition is no longer satisfied:
var i = 100; do { alert(i); i++; } while(i < 10)
If a while loop was given the same condition it would not run, as shown in the first while loop example.
For loops
A for loop often loops between a range. The range is specified by a condition:
for(i = 0; i < 10; i++){ alert(i); }
The first part in the brackets, i = 0
, is used to set an initial
value. It is entirely optional. It is also possible to reuse a variable:
var i = 5; for(i; i < 10; i++){ alert(i); }
The second part inside the brackets, i < 10
is the main condition.
This is important to ensure that the for loop has a condition at which to terminate on.
The third part of the for loop is also entirely optional. A loop with part 1 and part 3 omitted is shown below:
var i = 5; for(; i < 10;){ alert(i); i++; }
Note the semi-colons positions; one before the condition and one after.
For-in loops
The last type of loop found in JavaScript, the for-in loop, is used to iterate properties of an object. Objects were discussed in this tutorial here.
//Pet object var gismo = { name : "Gismo", type : "Cat", dob : "10/03/1998" }; //Pet object var petro = { name : "Petro", type : "Rabbit", dob : "29/04/2007" }; var i; for (i in gismo) { alert(gismo[i]); } for (i in petro) { alert(petro[i]); }
This is treating an object as if it were a mapped array whereby the key is the property name and the property value is the value.