AS3 - For loop gotcha

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;

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.


Flash, ActionScript-3, programming


Comment functionality has been disabled. Contact me on Twitter.

reelfernandes said:

var myObject;
for(i=0; i < 100; i++) {
    myObject = null;
    if(i % 2) {
        myObject = {};

Recent & Popular Articles

Browse All >