The OR ( || ) operator in AS3
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 ||= [];
Tags: ||, AS3, conditials, Flash, if, NaN, null, operator, or, or operator, undefined, value
October 25th, 2010 at 05:07
Very Helpful!!!!
August 8th, 2011 at 15:26
It is indeed a very helpful operator, It might help that people know when dealing with Global/class variables you would:
private var _myArray:Array;
private function doSomething(index:int ) : void
{
_myArray:Array ||= new Array();
_myArray.getItemAt( index);
}
August 9th, 2011 at 13:49
Oooooh thank you @MonkeyMagiic, that is dead sexy!
March 3rd, 2012 at 04:58
Nice post; i like handy tricks.