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.