Deconstructing the FOR Loop

AID: 1937
  • Status: Published

1330 points

  • Bymoagrius
  • TypeTips/Tricks
  • Posted on2009-11-11 at 06:08:36
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++)
                                    
1:

Select allOpen 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(;;)
                                    
1:

Select allOpen 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++);
                                    
1:

Select allOpen in new window



It's not entirely implausible:

var word="hallelujah";
for(var i = ""; i != word; i += word.charAt(i.length));
alert(i);
                                    
1:
2:
3:

Select allOpen 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++)
                                    
1:
2:

Select allOpen in new window



As is

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

Select allOpen 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++)
                                    
1:

Select allOpen 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;)
                                    
1:

Select allOpen 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() + " ";
}
                                    
1:
2:
3:

Select allOpen 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() + " ");
                                    
1:

Select allOpen 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())
                                    
1:

Select allOpen 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;)
                                    
1:

Select allOpen 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());
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window



Happy looping :)
Asked On
2009-11-11 at 06:08:36ID1937
Tags

loop

Topic

Scripting Languages

Views
809

Comments

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top Scripting Languages Experts

  1. mplungjan

    145,789

    Master

    0 points yesterday

    Profile
    Rank: Savant
  2. Ray_Paseur

    91,292

    Master

    0 points yesterday

    Profile
    Rank: Savant
  3. billprew

    63,376

    Master

    0 points yesterday

    Profile
    Rank: Genius
  4. RobSampson

    54,636

    Master

    0 points yesterday

    Profile
    Rank: Genius
  5. DaveBaldwin

    51,700

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  6. sedgwick

    43,950

    1,600 points yesterday

    Profile
    Rank: Genius
  7. leakim971

    43,184

    0 points yesterday

    Profile
    Rank: Genius
  8. dgofman

    36,400

    0 points yesterday

    Profile
    Rank: Genius
  9. COBOLdinosaur

    28,424

    0 points yesterday

    Profile
    Rank: Genius
  10. woolmilkporc

    24,200

    0 points yesterday

    Profile
    Rank: Genius
  11. ozo

    20,600

    0 points yesterday

    Profile
    Rank: Savant
  12. Qlemo

    19,984

    2,000 points yesterday

    Profile
    Rank: Genius
  13. chaituu

    19,100

    0 points yesterday

    Profile
    Rank: Sage
  14. tagit

    19,000

    0 points yesterday

    Profile
    Rank: Genius
  15. farzanj

    18,550

    0 points yesterday

    Profile
    Rank: Genius
  16. nap0leon

    15,094

    0 points yesterday

    Profile
    Rank: Sage
  17. paultomasi

    14,700

    0 points yesterday

    Profile
    Rank: Master
  18. StingRaY

    13,136

    0 points yesterday

    Profile
    Rank: Wizard
  19. jason1178

    13,044

    0 points yesterday

    Profile
    Rank: Genius
  20. HainKurt

    12,350

    0 points yesterday

    Profile
    Rank: Genius
  21. HonorGod

    11,600

    0 points yesterday

    Profile
    Rank: Genius
  22. ahoffmann

    11,136

    0 points yesterday

    Profile
    Rank: Genius
  23. basicinstinct

    10,800

    0 points yesterday

    Profile
    Rank: Genius
  24. leew

    10,030

    0 points yesterday

    Profile
    Rank: Savant
  25. ChrisStanyon

    9,864

    0 points yesterday

    Profile
    Rank: Sage

Hall Of Fame