Code Style Conventions for JavaScript

Code style conventions (much taken from http://javascript.crockford.com/code.html)

  • Do not use tab to format code. Use 4 spaces instead (configurable through a good IDE)
  • Avoid lines longer than 120 characters (again can be set through an IDE)
  • Class comments should be using /** */
  • Generally use line comments. Save block comments for formal documentation and for commenting out.
  • Give variables their own line and arrange them alphabetically (with nice line comments)
  • Define all variables at the top of the function.
  • Use camelCase for variable and function names
  • Global variables should be in all caps
  • Use of global variables should be minimized. Implied global variables should never be used.
  • Remove trailing commas if there is no other field following
  • Use {} instead of new Object(). Use [] instead of new Array().
  • It is almost always better to use the === and !== operators. The == and != operators do type coercion. In particular, do not use == to compare against falsy values.
  • Always name magic constants: http://stackoverflow.com/a/47902 if you use a number like '5' or '7' or '318' in your code, make it a constant and give it a good name at the top of the file

 

Beyond these, also use jsbeautifier.org, which will allow automatic code formatting. Use that before committing code.

---

Tip: If you're making a commit against a non-beautified file (existing file has lots of tabbing and spacing problems), do it in two pull requests.

(1) 1st pull request ... beautify the existing file without any of your changes.
(2) 2nd pull request .. add your changes (beautified).

The advantage is that it will be easy to tell that everything in pull request (1) is purely aesthetic (to fix code style), and everything in pull request (2) is functionality. Right now, it's hard to tell which lines of code are new functionality, because so many lines say they've been edited in the Diff.