Fancy Or
The lowly || operator in the hands of AS3 and JavaScript is not so lowly. Here’s a quick time saver.
I’d probably written code like this a thousand times before I knew this trick:
function printError(error:String): void { trace("Error: " + (error != null ? error : "Unknown error")); }
This would be the perfectly reasonable way of going about handling an invalid value by defaulting it to a valid value. It’s the only way to go in C or Java, but not in AS3 and JavaScript! The lowly || operator comes to the rescue:
function printError(error:String): void { trace("Error: " + (error || "Unknown error")); }
This usage of || works like this:
a ? a : b; // Equivalent to... a || b;
Sure, you could use the ternary operator or an if-else, but what if you were to do something you’d rather not have to re-do:
// This function is non-trivial and will take a while to run if you have a large array function getGreatestX(points:Vector.<Point>): Number { if (points == null || points.length == 0) { return NaN; } var greatestIndex:int = 0; var greatestX:Number = points[0].x; var len:uint = points.length; for (var i:int = 1; i < len; ++i) { var x:Number = points[i].x; if (x > greatestX) { greatestIndex = i; greatestX = x; } } return greatestX; } // This way is fast var ret:Number = getGreatestX(points); var greatestX:Number = !isNaN(ret) ? ret : 0; // This way gets it all on one line at the cost and without a // temporary variable, but it's painfully slow! var greatestX:Number = getGreatestX(points) ? getGreatestX(points) : 0; // This way is elegant, fast, and the point of this article var greatestX:Number = getGreatestX(points) || 0;
Once you know this, you’ll find yourself using it all the time. Lastly, the || operator works exactly the same in JavaScript, so feel free to use it there too.
#1 by Troy Gilbert on September 16th, 2009 ·
Hot dog, short circuit to the rescue! So, I guess if the first operand evaluates to anything “true” the second operand is never evaluated. Most excellent. I was always jealous that the Ruby guys have a similar shortcut for that ternary case.
#2 by jackson on September 16th, 2009 ·
Lua has something just like this too:
It just looks nicer and less weirdly-ternary in AS3. Definitely one of my favorite AS3 features now. :)
#3 by TokiZR on September 30th, 2009 ·
This is incredibly common if you’re writing Shell Script code.
Just not the same “||” notation to the operand but the very same idea.
#4 by jackson on September 30th, 2009 ·
Cool. Could you paste an example? I looked around a bit but didn’t find anything.