This repository has been archived by the owner on Mar 15, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 193
Style Guide
mattbasta edited this page Mar 26, 2013
·
3 revisions
- Soft tabs (4 space) indentation
- UNIX line endings
- UTF-8, always
- No BOM
- Always include a single line feed at the end of every file.
- Single quotes around strings (unless the string contains single quotes)
- In strings that contain both single and double quotes, prefer to escape the single quotes.
- Semicolons, always. This isn't CoffeeScript.
- Variable names for jQuery objects start with $. For example:
var $this = $(this);
- Element IDs and classes that are not generated by Python should be separated by hyphens, eg:
#some-module
. - One letter variable names are not allowed except for iterators.
- Do not create global variables.
- Use require.js to expose your code to other modules. Use events to expose your module's functionality when this isn't possible.
- Write JavaScript tests whenever possible.
- Prefer DOM methods over jQuery methods when DOM methods when it's clean:
is better than
document.getElementById('foo').innerHTML = 'bar';
$('#foo').html('bar');
All JS is to follow BSD KNF:
- Spaces on both sides of binary operators:
x + y z === 3 a ? b : c
- Spaces between keywords and parenthesized groups and before curly braces:
...except for functions, which have no spaces before parenthesized groups:
if () { for () { switch () {
function foo() { x = function() {
If your line becomes too long, wrap it. Try to vertically match up to parentheses, or simply wrap to a second line if you can:
// Bad
var x = this.is.a(really.long, line.that.you[should].wrap);
// Good
var x = this.is.a(really.long,
line.that.you[should].wrap);
// Better
var x = this.is.a(
really.long, line.that.you[should].wrap);
Wrapping many parameters downwards is messy. Prefer a single newline if possible:
// Bad
var x = this.is.a(really.long, line.that.you, should, wrap);
// Worse
var x = this.is.a(really.long,
line.that.you,
should,
wrap); // eww
// Good
var x = this.is.a(
really.long, line.that.you, should, wrap);
Wrap objects across multiple lines:
// Bad
var x = {foo: bar, this: that, zip: zap, high: low};
// Good
var x = {
foo: bar,
this: that,
zip: zap,
high: low
};
Prefer joining a list or augmented assignment over binary concatenation:
// Good!
var data = [
'foo',
'foo',
'foo'
].join('');
var data2 = 'foo';
data2 += 'foo';
data2 += 'foo';
data2 += 'foo';
// :(
var data3 = 'foo' +
'foo' +
'foo' +
'foo';
Binary concatenation is slower in all benchmarks as of writing this.