Skip to content

the Javascript logical OR assignment idiom

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 || [];
for (var i=0; i<arr.length; i++) {
    // 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)

{ 1 } Comments

  1. Brendan Eich | 23 February, 2007 at 3:28 am | Permalink

    You may be glad to learn that for JS2/ES4, ||= and &&= are being added as well. ||= is most useful of the two but there’s no reason to leave the assignment-op form of && out.

    /be

Post a Comment

Your email is never published nor shared. Required fields are marked *