First things first: this might be a bug in MXMLC. It sure did cause a bug in my program though! Read on for the stupid mistake that had me scratching my head.

One of my first articles on this site discussed AS3’s caching of the object you iterate over in a for-in or for-each loop. This is mightily handy. As such, I use it frequently to avoid the creation of temporary variables. It’s less typing, less bloat, and produces a cleaner result. Here’s how it looks:

for each (var name:String in getNames())
{
	trace(name);
}

Simple, eh? Well, one day I was doing some refactoring of function parameters and, in a typo, accidentally ended up moving the parentheses around such that one of the parameters was outside the function call. It looked like this:

for each (var name:String in getNames(), false)
{
	trace(name);
}

An honest typo. This should have never compiled. It did! As is starting to sound usual in my articles, there was no compiler warning or error to alert me of my silly typo. I therefore got to experience the joy of debugging this at runtime. What do you think the output would be for this:

trace("before");
 
// assume getNames() returns an array with length 2
for each (var name:String in getNames(), false)
{
	trace(name);
}
 
trace("after");

Well, the extra false seems to shut down the whole loop. The loop is never entered and you simply get:

before
after

At this point I figured that the comma operator was coming into play and that the expression getNames(), false was evaluating to false. So I tried replacing the false with a true. The results were unchanged. I also tried this with a for-in loop and the results were the same there too. So have I found a bug? Maybe. No where in Adobe’s documentation does it discuss this apparently-incorrect usage of the for-in and for-each loops. I only know what I’ve found out above, so my only advice to you is to watch out for this and simply never do it. Happy looping!