Archive for September, 2010

The OR ( || ) operator in AS3

Tuesday, September 21st, 2010

Here’s a quick tip: the OR operator ( || ) in AS3 does not return true if either condition evaluates to true; it returns the actual value of the first condition to evaluate to true.

What does that mean? Lets try an example:
This statement:

trace ( "foo" || "bar" );

will trace out the string “foo”, not “true” (in an if statement “foo” will evaluate to true).

This statement:

trace ( undefined || false || "bar" );

will trace out the string “bar”.

If no condition evaluates to true, it will return the last condition.

trace ( false || undefined || 0 || "" || NaN || null );

will trace out “null”.

This can be really handy when making sure variables are not uninitialized before using them.
Check out this example:

function doSomething(arr:Array, data:Object, path:String):void {
    this.args = arr || [];
    this.dataObject = data || {};
    this.dataUrl = path || "http://default.url";
}

And even sexier (thanks MonkeyMagiic):

this.args ||= [];