Javascript Variable Defaulting Beauty

I\’m reading through the Backbone.js source code and immediately found a beautiful snippet of code for defaulting a variable to a value. I just had to show how awesome it is in comparison to two other ways to default variables.

Assume the following snippets are syntactically correct. Don\’t worry about lacking var usage, closures, or anything like that – that\’s not the point of this post.

Method 1: The familiar, verbose way

if (! attributes) attributes = {};

This is the most familiar (almost language agnostic) way to default the value of attributes to {}. If attributes doesn\’t exist, then it will have the value undefined which is falsy (i.e., evaluates to boolean false). The not (!) of false is true, so we enter the branch – assigning the empty object to attributes.

Method 2: The typical, JavaScript way

attributes = attributes || {};

If the variable attributes has an existing value, we use that. Due to short circuiting, since a \”boolean or\” is true when one of the clauses/conditions is true, we can omit the evaluation of the second clause, {}. However, if there is no value in attributes, then it has the value undefined which makes the first clause of the \”boolean or\” expression false – triggering the evaluation of the second expression {}. The empty object is truthy and so it will be assigned to attributes.

Method 3: The Backbone.js way

attributes || (attributes = {});

If attributes exists, then we simply use its value. Now this is simply used to avoid the assignment (again, due to short-circuiting) – we\’re not actually doing anything with the value inside of attributes in the first clause. However, if the first clause is false (where attributes doesn\’t exist), we evaluate the second clause.

Evaluating the second clause, (attributes = {}) performs the assignment, which is truthy. That\’s it. Clean. Effective. And so damn clever.