Deconstructing the FOR Loop

We've all seen it often, and probably used it more often than we care to admit...

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

Open in new window

Used - in some variation - in some of the most common web- and RIA-development languages (ActionScript, JavaScript, PHP), looping in general (and the "for" loop, specifically) is commonly used but uncommonly understood.

What is the exact semantic of the "for" loop? Understanding precisely how it works isn't necessarily intuitive, but it is enlightening.

Consider this:


Open in new window

Ever seen it? Probably not. But it works, and I actually used exactly that in a real world application not long ago. Perhaps even more strangely, how about a for loop without following statements, like this (note the terminating semicolon):

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

Open in new window

It's not entirely implausible:

var word="hallelujah";
                      for(var i = ""; i != word; i += word.charAt(i.length));

Open in new window

The above would iterate 10 times, but the alert would only display once - "hallelujah".  Let's examine each apparatus:

the first apparatus - PART A - instantiation - sets i to an empty string.
the second apparatus - PART B - evaluation - instructs the loop to iterate until i equals the word variable.
the third apparatus - PART C - iteration - appends to the i string the next character from the word string.

The semicolon at the end of line 2 won't terminate the loop, but does indicate an absence of statements - so no actions occur until  line 3, the next executable statement: the alert.

The for loop is composed of 3 separate and distinct apparatus, separated by the semicolons: for( PART A ; PART B; PART C).

The first (Part A) is instantiation. You can declare and assign variables here, even execute single-line statements, or do nothing at all. If i has been declared earlier in the code, it doesn't need to be reinstantiated here. The following is fine:

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

Open in new window

As is

for(var i = 0, today = new Date(), isWeekend = (today.getDay() %  6) < 1; i < 10; i++)

Open in new window

The above would instantiate several variables:
i would be set to 0
today would be a new Date object
isWeekend would be a boolean value from the Date object that was just created, invoking the getDay method and applying a modulus operation.  The return is true if the day was Saturday or Sunday, false otherwise.

All these variables would be set before the first iteration, and referenced within the same apparatus.  Each could be further tested or manipulated in the statement block.

Anything before the first semi-colon functions exactly as if it were on a separate line of code.

The second apparatus, Part B, is the conditional test, evaluated before each iteration.  As soon as the statement appearing here returns false (in any incarnation of "false", including 0, null or an empty string), the loop ends. This is limited to a single statement, but it can use several operators and comparitors. E.G.,

for(var i = 0; i < 10 && (somevar != true || anothervar === false); i++)

Open in new window

the above loop would continue to increment the i variable until the following logic returned true:

i was no longer less than 10 AND either somevar was not true OR anothervar was explicitly false.

Part B is independant of Part A.

for(; anyvar == false;)

Open in new window

The above loop would continue to iterate until, for whatever reason, anyvar evaluated to false.

Lets say a developer has a text area that he wants to fill with random text to determine scrolling or spacing behavior.  assume this text element has a reference of "textField"; he might use the following to populate it:
for(;textField.height < 1000;){
                          textField.text += Math.random() + " ";

Open in new window

This could be even further shortened by ommitting the statement block entirely and incrementing the text property in the third apparatus, like so:

for(;textField.height < 1000; textField.text += Math.random() + " ");

Open in new window

Note the semicolon at the end of line 1 - this loop is a complete line of code that will execute (or compile) properly.

The third apparatus, Part C, is the iterative statement - this statement occurs during every loop, at the end of the statement block. It need not be an incrementation (i++),

for(var i = 0; i < 0.5; i = Math.random())

Open in new window

The above loop would set i to a random value between 0 and 1 until that random value evaluated to greater than 0.5.  That means it might happen once, or a dozen times, but likely would iterate once or twice.

As with the other apparatuses, this apparatus is not required.  Consider the following:

for(var i = 0; i < 10;)

Open in new window

This loop would have no built-in incrementation, and if the statement block did not either include a break statement (or a return statement if included within a function block), or assign a value to i that might exceed 10, it would result in infinite iterations.

Some of these examples may seem unlikely, but understanding how the mechanism works is an important step in understanding how to make the mechanism work how you want it to.

function Test(){
                      	var attempts = [];
                      		var attempt = Math.random();
                      		if(attempt > 0.5) return attempts;

Open in new window

Happy looping :)

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.