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: , , , , , , , , , , ,

4 Responses to “The OR ( || ) operator in AS3”

  1. Raj Says:

    Very Helpful!!!!

  2. MonkeyMagiic Says:

    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);
    }

  3. Flassari Says:

    Oooooh thank you @MonkeyMagiic, that is dead sexy!

  4. SHAMS Says:

    Nice post; i like handy tricks.