to Boolean || not to Boolean

Posted on Posted in actionscript, massive

I was looking for an simpler way of setting default values for function parameters in ActionScript2. The way I usually do this is something along the lines of:

function set value(s:String):Void
if(s == undefined) _value = s;
else _value = "default";

One option is using a logical OR operator to set default values. For example:

function set value(s:String):Void
_value = s || "default";

According to the flash LiveDocs a non-Boolean logical OR operation first converts the first operand (i.e. the expression on the left of the ||) to Boolean and if true returns the resolved value of the first operand. Otherwise it will return the resolved value of the second operand (expression on the right of the ||)

In the use case above it works fine, but after exploring the non-boolean implementation of the OR operator we found the following behaviour. In both the string literal (“hey”) and the string variable (s), the Boolean value equals true, but when placed in a logical OR operation they return different results. See below:

var s:String;
s = "hey";
trace(Boolean("hey") //true
trace("hey" || "dude");//"dude"
trace(s || "dude");//"hey"

Can anyone explain why the String literal is treated differently than a variable containing a String literal?

Oh and word up to Ian on this one for his input :)

[UPDATE] I know I could have gone with “toBoolean() || !toBoolean()” for the title but I think that is taking it a little too far.

[UPDATE 2] The only gotcha with this approach is with numbers as a value of zero converts to false.

3 thoughts on “to Boolean || not to Boolean

  1. for the number zero thing, should’nt you be using isNaN()? I’ll take a closer look at this in my spare time…

    Thanks, looks elegant..

  2. Absolutely – isNaN() is the most accurate way for checking that a number has a value. I’m just suprised that a string literal evaluates differently to a variable containing a string literal.

  3. trace(s || “dude”);//”hey”

    Null coalescence explains this one, as ‘s’ isn’t null, it returns the value of the object (“hey”)

    As far as the trace(“hey” || “dude”);//”dude” – this should be returning “hey”. Who knows..

Leave a Reply

Your email address will not be published. Required fields are marked *