As more Javascript code in Melange is going to be developed, here‘s a draft for code guidelines. These guidelines are inspired by PythonStyleGuide page (but adapted to JS), and from Code conventions for the Javascript Programming Language. In this very moment our code doesn’t respect them, but these are going to be strict rules when JavascriptRefactoring will come to an end. More infos on why these rules are important later.
As poor-written Javascript is more dangerous than as it‘s in other languages, we’re going to use Jslint to verify code conventions compliance. See JavascriptRefactoring for more information on how to use it.
More infos on how to write good Javascript code on Efficient javascript article and in Jslint code checking rules, some useful patterns and a great article about closures
Private and public/privileged vars/functions: we're going to use Module pattern, more info in JavascriptRefactoring page.
With statement: Do not use with statement. If you want to provide shortcuts, just create a variable that points to the object you want to access repeatedly. See explanations on why with statement is harmful
Iterations: as we've jQuery always loaded, use jQuery's each() function to iterate over objects/arrays. Do not use for...in loops, as they can lead to potential errors
Ajax calls: always use ?=_"+(new Date().getTime())
when invoking an URL to avoid caching issues
Global namespace pollution: at least avoid it (more infos when we come to an agreement for JavascriptRefactoring)
function foo() { };
This is unnecessary. But yes when you're storing an anonymous function inside a variable like this:
var foo = function () { };
Line length: 80 columns maximum. If you need to break one line, indent it by 2 spaces
Indentation: 2 spaces (no tabs)
Whitespaces: no whitespaces inside parentheses, brackets or braces
HTML Django templates: there should be no code in them
Comments: use JSDocToolkit style
Functions: no space between the name of the function and the parenthesis
Anonymous functions: 1 space between the word function and the parenthesis
Immediately invoked functions: wrap them between parenthesis, as in:
var myvar = (function () { return true; }());
Objects and arrays: use {}
to declare objects (not new Object()
) and []
to declare arrays (not new Array()
)
Variables: always use var, otherwise the variable will pollute the global namespace
Primitive objects: never extend their prototype
String concatenation: use
var concatenated = ["string1","string2"].join("");
instead of
var concatenated = "string1" + "string2";
It's usually faster for browsers and more beautiful when new lines are needed because line is too long.
If line is too long or you're going to store HTML, than indent it like this:
var foo = [ '<div>', ' <table>', ' </table>', '</div>' ].join("");
This won't break jsLint and helps understanding indentation in the HTML code as well.