Javascript Iteration
A traditional for-loop
A traditional for loop has three components:
1. The initialization: executed before the look block is executed the first time
2. The condition: checks a condition every time before the loop block is executed, and quits the loop if false
3. The afterthought: performed every time after the loop block is executed.
These three components are separated from each other by a ; symbol. Content for each of these three components is optional, which means that the following is the most minimal for loop possible:
Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) { return; } somewhere inside that for-loop to get it to stop running.
Usually, though, the initialization is used to declare an index, the condition is used to compare that index with a minimum or maximum value, and the afterthought is used to increment the index:
for (var i = 0, length = 10; i < length; i++) {
console.log(i);
}
Output
1
2
3
4
5
6
7
8
9
Using a traditional for loop to loop through an array
The traditional way to loop through an array, is this:
for (var i = 0, length = myArray.length; i < length; i++) {
console.log(myArray[i]);
}
Output
.
.
.
.
myArray.lenght
Or, if you prefer to loop backwards, you do this:
for (var i = myArray.length - 1; i > -1; i--) {
console.log(myArray[i]);
}
Output
4
3
2
1
There are, however, many variations possible, like for example this one:
var myArray = [1,2,3,4,5];
for (var key = 0, value = myArray[key], length = myArray.length; key < length; value =
myArray[++key]) {
console.log(value);
}
Output
2
3
4
5
A while loop
One alternative to a for loop is a while loop. To loop through an array, you could do this:
var key = 0;
while(value = myArray[key++]){
console.log(value);
}
Output
2
3
4
5
Like traditional for loops, while loops are supported by even the oldest of browsers.
Also, note that every while loop can be rewritten as a for loop. For example, the while loop hereabove behaves the exact same way as this for-loop:
for(var key = 0; value = myArray[key++];){
console.log(value);
}
Output
2
3
4
5