Loops

As you've seen, arrays can be a great way to store a lot of reusable data, but that's just the starting point; for and while loops provide functionality to iterate these arrays, access their values, and execute script with them.

The most common loop type in the JavaScript language is the for loop. A for loop usually consists of a variable that is assigned a numeric value, then that variable is used with a comparison operator to compare it against another value, and, finally, the numeric value is increased or decreased. The comparison in the for loop is typically determining whether the numeric value of the initial variable is less than or greater than another numeric value. Then, for the period of time that the condition is true, the loop runs and the variable is increased or decreased until the condition evaluates to false. Below shows an example of how to write a for loop that runs while a numeric value is less than the length of the array.

Structuring a for loop and iterating an array

var cities = new Array("Indore" , "Mumbai" , "Pune" , "New Delhi");

for(var i=0; i<cities.length; i++)

{

document.write("City is: "+ cities[i] +"<br/>");

}

The length property of an array provides a numeric value that is equal to the number of items in the array. Again, the trick is that the array starts with an ID of 0. Therefore, if there are 4 items in an array, the length is 4, but the indices in the array are 0, 1, 2, and 3—there is no 4.

Another type of loop is the while loop. They execute faster than for loops, but are appropriate in cases other than iterating an array, such as executing a script while a certain condition is true. Below shows how to write a while loop that executes a script while a numeric variable is less than 10.

Structuring a while loop

var i = 0;

while(i<10)

{

document.write(i +"<br/>");

i++;

}

Notice that the script in the while loop includes a line that iterates the numeric variable until the condition in the while loop is false. Without this line you would have an endless loop.