Skip to main content


Showing posts from March, 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 stri…