Marty
Marty

Reputation: 39456

Defining for loop iterator before the for loop?

Recently I'd been criticized for structuring my for loops like so:

var i:MovieClip;
for each(i in array)
{
    // be awesome
}

Or,

var i:uint = 0;
for(i; i<10; i++)
{
    // be more awesome
}

This reads better for me personally, yet I'm being attacked for it. Is there any difference?

Upvotes: 0

Views: 134

Answers (2)

trutheality
trutheality

Reputation: 23465

Old Answer

Yes: The way you're doing it, the variable lives on after the loop ends. Making sure the variable doesn't exist outside of the scope of the loop ensures that you never accidentally refer to it outside the loop.

Update:

At least that's how most languages do it. However, in ActionScript the for loop variable is in the scope of the parent! So there really is no difference in ActionScript.

Upvotes: 5

Kai
Kai

Reputation: 491

trutheality's answer is the best consideration in most languages, and a great response considering that this question wasn't tagged actionscript-3 until later.

However Actionscript uses variable hoisting where variables defined anywhere in the function are scoped to that function rather than its inner most block. This blog post describes it well, and it's mentioned in the docs on variable scope. Due to hoisting, there is no difference in Actionscript between defining the variables before or inside the loop.

To show how crazy this can get, you can even define the variable after the loop:

for (i = 0; i < 5; i++) {
  trace(i);
}
var i:int;

Upvotes: 3

Related Questions