<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Deconstructing the FOR Loop

Published on
8,604 Points
2,604 Views
Last Modified:
Approved
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:

for(;;)

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));
alert(i);

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 = [];
	for(;;){
		var attempt = Math.random();
		attempts.push(attempt);
		if(attempt > 0.5) return attempts;
	};
};
alert(Test());

Open in new window


Happy looping :)
0
Comment
Author:moagrius
0 Comments

Featured Post

CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Join & Write a Comment

Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Other articles by this author

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month