Wednesday, November 2, 2011

[js] Short-circuit trickery

Your function has a string argument, arg, that may or may not be supplied from the caller. You want to assign result with the value of arg, if it exists, or the string 'none', if it doesn't.

Quick, how do you do this?

var result;
if (arg)
  result = arg;
else
  result = 'none';

One point.

var result = arg ? arg : 'none';

Two points.

var result = arg || 'none';

Three points for style! This kind of operation is formally known as null coalescing, and for the longest time I was unaware that Javascript had it.

Hold on, how does this even work? You're using the short-circuit OR operator. Isn't the result of a logical operation either true or false?

You know, that's a good question. I had always assumed so, and you'll even find Javascript resources on the web stating the same. But it isn't so. In Javascript, the result of short-circuit OR will be the actual value of the first operand that evaluates as true (if one of them does, that is—if not, you'll get back the value of the last operand.)

result = 4 || 'fred';     // result = 4
result = true || 'fred';  // result = true
result = 0 || 'fred';     // result = 'fred' because 0 evaluates as false
result = false || 0;      // result = 0

Does the short-circuit AND also result in an actual value? Why, yes, it does. If all operands evaluate as true, you'll get the last value; otherwise, you'll get the value of the first operand evaluated as false. And this lends itself to another nice trick.

name = rec && rec.formatName();

This is equivalent to the slightly clumsier:

if (rec)
  name = rec.formatName();

No comments: