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.

Tuesday, February 28, 2006

Shades of Truth and Falsity

Earlier, I mentioned that you never need new Boolean to create a boolean value. That's because Javascript rarely needs boolean values at all; it will gladly make boolean decisions based on any type of variable--numbers, strings, even objects!

When used in a context that needs a boolean value, Javascript considers these values--and only these values--to be false:

false (the boolean kind)
0 (numeric zero)
null (the null value)
undefined (the undefined value)
NaN (the not-a-number value)
"" (an empty string)

Anything else is considered to be a true value. Anything. Really. Memorize the entire set of potentially false values, it will make your Javascript better. Be careful, Javascript will not automagically convert values from another type when it evaluates their booleanosity. String values of "0", "false", or "null" evaluate to true. In contrast, an expression like parseInt("0") returns numeric zero and evaluates to false. Then again, parseInt("null") returns NaN (it's not a number, obviously) and that is also false.

One common use of the undefined value is to check for the existence of properties in an object. Thus, you'll often see if ( document.getElementById ) to check browser support for a DOM function. The value will either be undefined or a function object, which are interpreted as false/true respectively. Note that this trick won't work to check for undefined variables. If a variable has never been defined, Javascript will give you an error. The safe way to check for a variable that has never been declared is to use typeof(nosuchvar)=="undefined".

It's worth learning the boolean drill backwards and forwards, because knowing these rules comes in mighty handy with the next topic: short-circuit evaluation.

Knowledge Base

The best way to get going with any language is to start with some existing code; tweak it, extend it, rewrite it, and break it. It's good to have some background information for that effort though, which is where Javascript references come in handy.

If you want just the facts without third-party interpretations, go directly to the ECMA 262 (EcmaScript) standard. Like many standards documents, though, it can be very dense for a programmer. ECMA 262 is written as though the reader's job is to implement a Javascript compiler, which means you can count its primary audience using just your fingers. Although ECMA 262 serves as the Supreme Court for correct Javascript behavior, you're better off going to a lower court for intelligible opinions.

By far, my favorite dead-tree book on Javascript is O'Reilly's Javascript: The Definitive Guide. It includes a thorough overview of language features, plus a comprehensive reference section for Javascript functions and objects. Every programmer should have a copy of this book and give it a good looking-to.

Every programmer's dirty little secret today is that Google serves as the primary language reference. That works pretty well for a quick check of the parameters for a particular object, but I do have a few favorite reference sites. The one at W3Schools is pretty comprehensive, but in the process goes into detail about features you'll absolutely never need, like new Boolean(value). The DevGuru guide uses a very different organization but is also relatively comprehensive. However, it also has some errors in the details that I'll cover in future entries.


I've spent a lot of the past decade writing Javascript. The language was rough at first--just like the browsers that implemented it--but over time it's evolved into an incredible environment. I particularly like the way it filched features from Perl, another language that I happen to like.

If I had to reduce my Javascript programming philosophy to three words, I'd choose the title of Paul Graham's essay, "Succinctness is Power". Every profession--medical, legal, engineering, programming--has shorthand incantations that save time and reduce ambiguity. As outsiders, we look at another profession's shorthand with disdain and confusion. Some of the methods I advocate here will probably trigger objections along the lines of "That's not clear enough, it's better to spell it out so everyone understands what you're doing." I say that it's worth learning the shorthand of Javascript, it will serve you well in the long run.

Mainly, I've created this blog as a fun outlet for little tidbits about programming in Javascript. In particular, it will discuss my favorite features of Javascript, ones I think deserve more attention. Javascript isn't just in browsers, either; you can write programs for Windows Scripting Host (WSH) and Active Server Pages (ASP) in Javascript too. I have a few tidbits for Javascript in those environments as well.