Helping ordinary people create extraordinary websites!

JavaScript For Loop

Iteration is a common element of JavaScript, and is achieved with the for loop.

Basic iteration with for

for (i=0;i<10;i++) {

This will output all the numbers between 0 and 9. The for loop is the basic iteration, or repetition, structure in JavaScript. It allows you to execute a block of code a given number of times. You could also achieve this above example with a while loop:

var i = 0;
while (i<10) {
i = i + 1;

However, as you can see, the for loop is cleaner and easier to read. It is also slightly faster.

A for loop has three parts: the assignment, the condition, and the step. The assignment initializes a variable that will be used to count the iteration. The condition states what condition must be passed for each iteration of the for loop, and the step states what will happen at the end of each iteration. Here is the syntax:

for (assignment; condition; step) { ... }

So, when you first create a for loop, JavaScript will run the assignment and create the variable. It will then keep executing the code within the curly braces, running the step at the end of each iteration, for as long as the condition is true.

Advanced for and infinite looping

Any of these parts can be replaced with a valid JavaScript statement, as long as it makes sense. For example, the condition can be any of the conditions we used for while and for loops. Instead of i<10, you could use i != 10. Also, you can omit one or more, however you must leave the semicolons in.

Finally, you can break out of the for loop at any time using the break; statement. For example, this is perfectly valid:

for (;;) {

This example would run forever without the break, but it will reach the break on the first iteration and finish there. A for (;;) is an infinite loop. This can be used when you want to keep going until something happens, at which point you can break.

Now that we've covered the main loops, let's move on to JavaScript comments.

« JavaScript While Loop JavaScript Comments »

More JavaScript Tutorials:
» Building a Javascript Array
» Event Handlers and Callback Functions in JavaScript
» Hide and Display Content On Demand
» Finding the Length of a String in JavaScript
» Change Form Field Values, On The Fly, with JavaScript
» Validating Form Input - II
Tell a Friend


Developer Resources