0

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?

Marty
  • 39,033
  • 19
  • 93
  • 162

2 Answers2

5

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.

trutheality
  • 23,114
  • 6
  • 54
  • 68
  • Though I can still access variables that have been defined in a for loop from outside of the loop.. – Marty Jun 02 '11 at 04:42
  • Really? Well I answered before you specified the language, and in most languages you can't. – trutheality Jun 02 '11 at 04:44
  • Ah, sorry. Even if I try two for loops (lets say the above except with i defined in the for() statement) then there's a conflict with i. – Marty Jun 02 '11 at 04:46
  • Oh... after reading [this](http://stackoverflow.com/questions/4479896/for-loop-variable-scope-confusion) I'm going to update my answer. – trutheality Jun 02 '11 at 04:54
  • I'll give you this one 'cause it was my bad for not labelling the question correctly and your first answer will be good to keep in mind down the track - thanks :) – Marty Jun 02 '11 at 05:00
3

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;
Kai
  • 491
  • 2
  • 9
  • Gross - I don't like that at all. Though it's useful for me the way ActionScript does this because you can break a loop and return the value of i afterwards (as it was when the loop was broken). – Marty Jun 02 '11 at 05:02
  • I don't like it at all either. I'm not sure why they would break from convention in such a subtle way. Usually people don't figure this out until they run into inexplicable compiler errors. – Kai Jun 02 '11 at 05:04