-
Notifications
You must be signed in to change notification settings - Fork 1
Javascript coding convention
1337 edited this page Jul 9, 2012
·
5 revisions
- Follow Douglas Crockford's JavaScript guidelines, unless otherwise specified below.
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.
- 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.
- No new lines for braces. In other words, do not do this:
var jack = function ()
{
return true;
};
CamelCase
propName
varName- at least two meaningful characters.
- use only
//for handwritten comments. - use
/* */block comments only for machine-directives, e.g. includes, tests, doxygen.
This one is absolutely bullet-proof, and is recommended on all client-sided pages.
- Never attempt to leave out "optional" semicolons.
- Never attempt to use stupid tricks like
!function () { ... }()to omit semicolons.
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 // functions are, in fact, valid keys
};