This article is sort of a follow-up to my article on Flexible Loop Syntax. This was reported to my by a coworker who spotted the anomaly. I guess he had done with if the same sort of thing that I had done with for. Read on for a little insight into how the comma operator interacts with the if statement.

My coworker’s claim was that the comma operator acts like the && operator in an if statement. So I tried this out:

if (true, false)
{
	trace("true, false");
}
if (false, true)
{
	trace("false, true");
}

If his claim were correct, neither would be traced. Instead, we get:

false, true

So it seems that only the second operand to the comma operator is being used to decide truth for the if statement. Let’s test that out with some more experiments:

if (true, false, true)
{
	trace("true, false, true");
}
if (false, true, false)
{
	trace("false, true, false");
}
if (false, false, false, false, false, true)
{
	trace("false, false, false, false, false, true");
}
if (true, true, true, true, true, false)
{
	trace("true, true, true, true, true, false");
}

Which prints:

true, false, true
false, false, false, false, false, true

So it seems as though we were correct originally when we said that only the second operand to the comma operator is used to determine truth. With more commas we are essentially just building up one big nested comma operator. Here are rewritten versions of the last two tests to demonstrate this:

if (((((false, false), false), false), false), true)
{
	trace("((((false, false), false), false), false), true");
}
if (((((true, true), true), true), true), false)
{
	trace("((((true, true), true), true), true), false");
}

This, as expected, yields the same results:

((((false, false), false), false), false), true

So maybe the if and for statement syntax is not so flexible after all, but instead it is the comma operator syntax that can be used in unexpected places. If this puzzled my coworker and I, I’m sure it’s puzzled some of you out there. This is that it seems to be an ECMAScript family feature since it applies equally to AS2, AS3, and JavaScript so you’ll probably have to keep this in mind whenever you’re programming for a browser. If there’s anyone out there who has a good use for this feature, feel free to post it in the comments with code formatting blocks like this:


<pre lang="actionscript3"
// code
</pre>