Javascript For: Loops in Javascript

The most common type of loop in javascript is probably the for loop.

There are two common ways of using for. The first way involves using a variable to count however many loop iterations you want to make.

Note that you can always terminate a loop early using break, or you can skip the rest of the statements in the loop and go to the next iteration with continue.

Here's an example.

A Simple For Loop In Javascript



var text = '';
    
for(var i=0; i<10; i++) {
    text += i + ' ';
}
    
alert(text);






Using For Loops With 'In' to Iterate Over an Array in Javascript



You can also use for with in to iterate over the elements of an array. The loop variable you specify will be set to each index of the array in turn.

var fruits = ['apple', 'orange', 'pear'];

var text = '';

for(var i in fruits) {
    text += i + ': ' + fruits[i] + 'n';
}

alert(text);







While Loops in Javascript



In case you're bored with for loops, you can always use while instead. while lets you loop as long as some condition is true.

For example:

var fruits = ['apple', 'orange', 'pear'];

var text = '';

// pop removes and returns the last
// element of the array.
var fruit = fruits.pop();

while(fruit) {
    text += fruit + 'n';
    
    fruit = fruits.pop();
}

alert(text);







Do ... While Loops



You can also use do ... while loops; these are the same as while except that, since the loop condition is only tested at the end of the loop, the loop is guaranteed to always execute at least once.

var fruits = ['apple', 'orange', 'pear'];

var text = '';

var fruit = fruits.pop();

do {
    text += fruit + 'n';
    
    fruit = fruits.pop();
}
while(fruit)

alert(text);