- Recommend to follow this style https://github.com/stephenplusplus/javascript-style
- Chained methods should be split into multiple lines
// Not preferred
survey.sync()
.filter(function (survey) {
return record.expired;
})
.map(function (survey) {
survey.records = survey.data.length;
return survey;
})
.save();
// Prerred
var expired = function (survey) {
return record.expired;
};
var counts = function (survey) {
survey.records = survey.data.length;
return survey;
};
survey.sync()
.filter(expired)
.map(counts)
.save();
- Multiple var statements
- if else
if (err) {
return res.json(400, { errors: ['There are no incidents'] });
}
// if you have a large expression to evaluate, write a method
var executable = function () {
return notChanged &&
!survey.changed &&
(!survey.expired || survey.expires === 'never');
};
if (survey.changed) {
// do something
}
else if (executable()) {
// do this
}
else {
// do something else
}
- Ternary operators
var exp = this.val1 < this.val2
? 'good'
: 'bad';
- Spacing and other preferred practices
// Good
if (err)
// Bad
if(err)
// Good
function () {}
// Bad
function(){}
// Good
var sum = val1 + val2
// Bad
var sum = val1+val2
// Bad
var path = '/organizations/' + organization._id + '/surveys/' + survey._id
// Good
var path = [
'/organizations/',
organization._id,
'/surveys/',
survey._id
].join('/');
// Good
function expired () {
return survey.expires < new Date();
}
// Bad
function expired () {
return survey.expires < new Date();
? true
: false;
}
- Precendence for requiring
var http = require('http'); // native modules first
var mongoose = require('mongoose'); // npm modules second
var config = require('config'); // modules that are required via NODE_PATH third
var fmt = require('./format-date'); // local modules fourth
var oauthHelper = require('../../oauth-helper'); // relative modules last
sname_case
for naming database attributes
camelCase
for variables and methods.
Constructors
start with caps.
file-names
and folder-names
must use hyphens and not underscores or caps.