What strings are true? The answer may surprise you.

AS3 and JavaScript allow for type conversion in a variety of scenarios. Sometimes strings can type type converted, such as these functions:

function isStringTrue1(str:String): Boolean
{
	// Implicit type conversion of str from String to Boolean
	if (str)
	{
		return true;
	}
	else
	{
		return false;
	}
}
function isStringTrue2(str:String): Boolean
{
	// Explicit conversion of str from String to Boolean
	return Boolean(str);
}

The above functions are equivalent, but the latter is more elegant. So the question is this: which strings are true? Consider these:

trace(Boolean(""));
trace(Boolean("something"));
trace(Boolean("true"));
trace(Boolean("false"));

If you think that any non-null String is true, as in C or Java, then you would answer that all of the above are true. You’d be wrong though! If you think that type conversion is taking over and looking at the contents of the strings, then you’d think that the last and possibly the first are false and the others are true. You’d also be wrong! Here are the correct answers:

trace(Boolean("")); // false
trace(Boolean("something")); // true
trace(Boolean("true")); // true
trace(Boolean("false")); // true

As it turns out, the only non-null String that is false is the empty string. Knowing this, we find that there is an alternative way to check for a “valid” string, usually considered to be one that is non-null and not empty:

function isStringValid(str:String): Boolean
{
	return Boolean(str);
}

It’s such a simple function, you may end up inlining it as it’ll be faster, probably require less typing, and not add to bloat. One last thing: all of the above applies to JavaScript as well. Just be sure to take out all the types. :)