I recently discovered that in Javascript v1.2 and later, the output of the logical OR operator is not simply boolean true or false, but rather:

  • the value of first operand, if the operand can be converted to any of the Javascript variants of “true” (anything other than: false, 0, null, undefined, or the empty string) or,
  • the value of the second operand

I’ve found this useful for a number of situations:

lightweight normalization of cross-browser differences

// determine upon which element a Javascript event (e) occurred
var target = /*w3c*/ e.target || /*IE*/ e.srcElement;

provide a default value

var arr = anObject.aPossiblyNullArray || [];
    // do something (or not)

The code above is likely second nature to people coming from a C or Perl background, but when you’ve been using a language like Java for a few years, it’s easy to forget about this sort of idiom.

(idiom source: Javascript: The Definitive Guide, 5th Ed. – page 72)