JavaScript has no official style guide, but maintaining a consistent style within a project is important. For this book, I’ve adopted the following (very common) conventions:
Two-space indentation
camelCase identifiers
Semicolons at the end of every expression, except function definitions
More esoterically, I’ve adopted a special convention for indentation in a chain of function calls, based on a proposal by Reg Braithwaite. The rule is, essentially, that two function calls in a chain have the same indentation level if and only if they return the same object. So, for instance, I might write the following:
| $('#container > ul li.inactive') |
| .slideUp(); |
jQuery’s slideUp method returns the same object that it was called on. Thus, it isn’t indented. By contrast:
| var $paragraphClone = $('p:last') |
| .clone(); |
Here, the clone method is indented because it returns a different object.
The advantage of this convention is that it clarifies what each function in a chain is returning. Here’s a more complex example:
| $('h1') |
| .first() |
| .addClass('first') |
| .end() |
| .last() |
| .addClass('last'); |
jQuery’s first and last filter a set down to its first and last elements, while end undoes the last filter. So, end is unindented because it returns the same value as $(’h1’). (last is allowed to occupy the same indentation level as first because the chain was reset.)
This approach to indentation is especially useful when we’re doing functional programming, as we’ll see in Chapter 4, Flow Control with Async.js.
| [1, 2, 3, 4, 5] |
| .filter(function(int) { return int % 2 === 1; }) |
| .forEach(function(odd) { console.log(odd); }) |
3.14.246.207