Skip to content

Javascript coding convention

1337 edited this page Jul 9, 2012 · 5 revisions

tl;dr

Line Length

Strictly less than or equal to 80 characters, unless any of these applies:

  • it is impossible to break the line up to below 80 characters
  • it looks uglier than before you trim it down to 80 characters
  • line is a pure string literal
  • line is a regular expression.

Note that the Python coding convention dictates a line length of at most 79 characters, so it is advised that you follow the 79-character rule for Javascript as well.

Tabs and spaces

  • no tab characters of any kind shall be found in our code.
  • no trailing spaces of any kind shall be found in our code.
  • indentation: 4 hard spaces.
  • Example use of spaces, indentations and newlines:
var j = function (param) {
    (function ($) {
        j($);
    })(this);
};

In the example above, all spaces, brackets and indentation styles are intentional.

Braces

  • No new lines for braces. In other words, do not do this:
var jack = function () 
{
    return true;
};

Class Names

  • CamelCase

Property Names

  • propName

Variable Names

  • varName
  • at least two meaningful characters.

Docstrings/Comments

  • use only // for handwritten comments.
  • use /* */ block comments only for machine-directives, e.g. includes, tests, doxygen.

Tag style

This one is absolutely bullet-proof, and is recommended on all client-sided pages.

Semicolons

  • Never attempt to leave out "optional" semicolons.
  • Never attempt to use stupid tricks like !function () { ... }() to omit semicolons.

Data types

Objects

Never use variable keys, as they cause unnecessary confusion. Do:

var obj = {
    'thing': '1',
    'thing2': false,
    'thing3': true
};

Don't:

var obj = {
    thing: '1',
    true: false,
    function(){}: true
};

Clone this wiki locally