Wednesday, March 01, 2006

Fun with Short Circuits

Just because an operator or statement needs a boolean value does not mean that it converts the value to a boolean. Instead, it merely interprets the value in a boolean way according to the rules. That's an especially important distinction when dealing with the two short-circuit pseudo-boolean operators, && and ||.

Let's look at && first, using this example:

var boys = { Manny: 1, Moe: 2, Jack: 3 }; var str = ""; for ( var pep in boys) str += (str && " ") + pep; alert(str);

This code takes the names of the properties in the PepBoys object and joins them into a single string separated by spaces. But what's going on with the && operator? The first time through the loop, str is an empty string which is false in Javascript's book. Since && is a short-circuit operator, the second operand of a space doesn't come into play. However, instead of returning false, it returns the actual value of str--the empty string. That's just what we want, since otherwise the final string would have a leading space. On subsequent times through the loop, str is non-empty and thus true, so the && operator continues on to return the space (which also happens to be true but it would be returned regardless). Again, just what we want!

Oh, and that wouldn't be my favorite way to join strings. I'd do it this way instead:

var arr = []; for ( var pep in boys) arr.push(pep); alert(arr.join(" "));

Though && is cool, the opportunities to use it aren't that common. On the other hand hardly a dozen lines can go by without using the || operator, so next time I'll give it the exclusive post it deserves.