"Or" Inline Conditionals
Most of us are familiar with the ? : inline conditional, or ternary operator, as a short cut for if then
if (boolean) {
a = "foo";
} else {
a = "bar";
}
a = boolean ? "foo" : "bar"
There is also a lesser known "or" inline conditional that you can use:
a = foo || bar;
What this does is sets a = to foo if foo resolves as true, and bar otherwise. For instance, if foo were an empty string, it would resolve as false, but if foo is an empty new String() object, it would resolve as true.
This is useful when you want to use a default value if an expected value is undefined/null/0/"".
function init(str:String):Void
{
var myStr:String = str || "Default String";
}
While inline conditionals and inline or conditionals both return their results, you can also use them without defining a pointer.
bool ? a = "foo" : b = "bar"; bool ? foo() : bar(); foo() || bar();
The last one will call foo and if foo returns anything that resolves as false, it will call bar, otherwise it won't. I personally haven't found a use for it and for code readability would advise against it. However, it is a good example of how the inline conditionals work.
Posted in Actionscript, Flash, Tips/Tricks
February 7th, 2007 at 8:36 am
Nice one Steven. I just came across this conditional in Peter Elst|Todd Yard's Object-Oriented Actionscript for Flash 8, and was wondering about its details.
May 7th, 2007 at 8:31 am
I stumbled across something like that in a book on Lua coding and use it in AS ever since…Nice.
May 27th, 2007 at 3:22 pm
Hi, if I'm not mistaken, the rules for evaluating whether the expression is true or false are the same.
My understanding is that a String object and a string literal are actually two very different types. While a string literal is a primitive type, a String object is a complex-type (or composite-type or reference) that wraps a primitive value - a string literal.
As you point out, the values undefined/null/0/"" are evaluated to false; any other value evaluates to true. An empty string literal would then evaluate to false. However, a String object with an empty string as a value would not evaluate to false, cause the object itself is not undefined, null, 0 or "".
A simple example to illustrate the point:
var objFoo:String = new String("");
var litFoo:String = "";
if(objFoo) {
trace("objFoo evaluates to true");
} else {
trace("objFoo evaluates to false");
}
if(litFoo) {
trace("litFoo evaluates to true");
} else {
trace("litFoo evaluates to false");
}
The result in the output panel is:
objFoo evaluates to true
litFoo evaluates to false
So, I believe the same rules apply to both the inline conditional and the if statement.
Cheers
PS: I'm looking forward to try your framework!
May 27th, 2007 at 5:05 pm
Thanks for pointing out that error. I've updated my post to reflect it.