I recently read Code Conventions for the JavaScript Programming Language from Douglas Crockford, the guy that discovered JSON. I was really surprised to see such an old convention as Avoid lines longer than 80 characters. For the past years, I didn't follow this convention until a couple of months ago when I accidentally clicked the option to show the 80 chars limit on gEdit and didn't bother to unclick it. Without noticing it, I began writing with a limit of 80 chars and it made my code much clearer. Plus, nobody likes to scroll horizontally, even programmers.

Functions

This one is simple. You should just avoid having a long list of arguments by putting them on 2 lines with a tab (or 2 spaces) on the second line.

Use hashes for optional arguments

A good way of avoiding long list of argument is to put optional arguments in a hash. Suppose that the first two arguments are required and the other ones are optional. You could write something like this.

Chains

In jQuery, we often have to write a long chain of command. Here is how I write it to make it clearer.

One-liner IF

The more I code, the less lines of code I want. I write a lot of Ruby and I like one-liners. Here's a little tip on one-liners ifs in javascript.

Tabs are dead, use 2 spaces

When I was a brand new programmer, tabs were all the rage. The bigger your tab space, the better. I was using a 8 spaces tab length at the time. And those were hardcore tabs too, not pseudo-tabs created by adding spaces one after the other. The best programmers were even uselessly indenting some statements as in this :

These days, most editors have the “Insert spaces instead of tabs” and “Tab width” options. Look for them and do the following : 1. Check the box beside the “Insert spaces instead of tabs” 2. Write “2” inside the “Tab width”

comments powered by Disqus