Gotcha: using shorthand notation with boolean operators

Scris de in data de 26 March 2010
0 comentarii

In ActionScript (as well as JavaScript), the boolean AND and OR operators have a special meaning. That is, they don’t necessary return true or false, but return one of the operands.

var op1:Boolean = true;
var op2:int = 2;
var op3:Object = null;

var result_1or2:Object = op1 || op2;
trace(result12); // output: true
var result_1and2:Object = op1 && op2;
trace(result); // output: 2
var result_3or2:Object = op3 || op2;
trace(result); // output: 2
var result_3and2:Object = op3 && op2;
trace(result); // output: null

So, if you decide to execute write something really terse, like

var result:Boolean = validateSomething() && validateSomethingElse();

and expect both functions to run, then you might be in for a surprise. If the first operand evaluates to false (false, null, 0 or "") then the second part is not executed.

The same caveat applies to the shorthand operator a &&= b(), which basically expands to a = a && b(). So if a is “falsy”, b() is not executed. So be careful with logical operators and don’t abuse them or they’ll bite back!

You have been warned.


No Comments comment feed