AS3 – For loop gotcha

April 16th, 2009

I knew the compiler moved variable declarations made in a for loop outside of the loop, but I’ve never come across a situation where that mattered. Rather I just enjoyed the fact that it made things run faster, and allowed me to maintin legible code. However, I have come across a situation where this does matter. Because the declarations are moved out side, values will carry over between each iteration. We can see this in the following code:

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

This will trace out the numbers 1-10, despite the fact that int’s have a default value of 0. So when does this matter? If you have a situation where a variable may or may not be set, after the it is initially set, it will never null. For example:

for(var i:int=0; i<10; i++)
{
    var myObject:Object;
    if(i%2 == 0) myObject = {};

    if(myObject) doSomething();
}

In this is piece of code (please don’t actually code like this) myObject will always exist, so doSomething will always execute. The solution is very simple, just declare it with a null value like so:

var myObject:Object = null;

Anyways, I thought it was worth documenting, hopefully doing so saves somebody some head scratching.

Leave a Reply

This site uses icons created by Mark James, www.famfamfam.com/lab/icons/silk