Loops In JavaScript

Open Source 25 Mar , 2013  


loops_iconJavaScript performs several types of repetitive operations, called “looping”. Loops are set of instructions used to repeat the same block of code till a specified condition returns false or true depending on how you need it.

So guys Loops are real menaces!  The vast majority of browser crashes are caused by badly constructed JavaScript loops. – I don’t have any numbers to back this up but I think it seems like a pretty reasonable statement. Even if loops aren’t the number #1 cause they’re probably still pretty near the top.

You can see how much is at stake here; constructing a loop incorrectly can leave a browser fighting for breath, so it’s a good idea to learn the basics before you go trotting off in the wrong direction.

The WHILE statement:

This is probably my favourite statement in JavaScript, and it’s probably the most useful one you’ll ever come across.

// A typical while loop
var i = 0;
while ( i < 10 ) {
    // This block will be executed 10 times
    console.log( "I am on step " + i );

    // increment i

It’s pretty simple too: as long as the passed condition evaluates to true the statement will continue to execute over and over again, it will only stop when the condition evaluates to false. Here’s a pretty cool example:

// #1 : regular
var myArray = ['apple','orange','mango'],
    length = myArray.length,
    counter = 0;
while (counter < length) {
    alert ( myArray[counter] );
} // alerts 'apple', then 'orange', then 'mango'

// #2 : in reverse
var myArray = ['apple','orange','mango'],
    length = myArray.length;
while (length--) {
    alert ( myArray[length] );
} // alerts 'mango', then 'orange', then 'apple'

What About Performance ?

From research it has been discovered that looping using a set of DOM elements or any array for that matter, using a reverse while loop is faster than any of the other well-known alternatives for instance a standard FOR loop. One consideration you must also take is that of caching. Always cache the length of the array if you’re using it to construct a loop. And, if you need to access a property of an object within a loop you should cache that to. By ‘caching’ I just mean assigning a value to a variable.

The do-while Loop

These types of loops are quite rare since only few situations require a loop that blindly executes at least once and that it’s quality too sometimes..

Regardless, it’s good to be aware of it.

// A do-while loop
do {
    // this loop's body will still execute once.
    alert( "Hi there!" );

} while ( false );

The FOR Statement

The FOR statement is the most commonly used method for looping through arrays. I think people see it as a nicer alternative to the WHILE statement because it seems more self-contained, have a look:

var myArray = [1,2,3,4,5,6];
for ( var i = 0, arrLength = myArray.length; i < arrLength; i++ ) {
    // Notice that we've named the counter 'i'
    alert ( myArray[i] );

A for loop is made up of four statements and has the following structure:

for ( [initialisation]; [conditional]; [iteration] ) {

    [ loopBody ]


The initialisation statement is executed only once, before the loop starts.

The conditional statement is executed before each iteration and if the conditional statement evaluates to a falsy value, then the loop stops.

The iteration statement will involve incrementing or decrementing a counter and thus bringing the loop closer to its end.

The loopBody statement is what runs on every iteration.  Typically, there will be multiple statements that need to be executed, and should be wrapped in a block .


So guys As far as speed and performance goes, the same rules apply! Anything used within the statement or within the condition must be cached if it’s a property (i.e. something you would access like this):

// THis is BAD:
for (var i = 0; i < myArray.length; i++) {
    foo.bar.special.method ( myArray[i] );

// It goes GOOD:
for (var i = 0,
         fn = foo.bar.special.method,
         length = myArray.length; i < length; i++) {
    fn ( myArray[i] );

// Better, In my opinion 🙂 :
var i = 0,
    fn = foo.bar.special.method,
    length = myArray.length;

for (; i < length; i++) {
    fn ( myArray[i] );

The last chunk of code does exactly the same as the second (‘GOOD’) except the variables are declared outside the FOR statement making it a little more readable.

Breaking and continuing :

Usually, a loop’s termination will result from the conditional statement not evaluating to true, but it is possible to stop a loop in its tracks from within the loop’s body with the break statement.

// Stopping a loop
for ( var i = 0; i < 10; i++ ) {
    if ( something ) {

You may also want to continue the loop without executing more of the loop’s body. This is done using the continue statement.

// Skipping to the next iteration of a loop
for ( var i = 0; i < 10; i++ ) {
    if ( something ) {

    // The following statement will only be executed
    // if the conditional 'something' has not been met
    console.log( "I have been reached" );


, , , ,