Work in progress
// Wrong
var foo = 'bar'
// Right
var foo = 'bar';
// Wrong
var foo = "bar";
// Right
var foo = 'bar';
// Wrong
if (true)
{
console.log('losing');
}
// Right
if (true) {
console.log('winning');
}
// Wrong
var keys = ['foo', 'bar'],
values = [23, 42],
object = {},
key;
while (keys.length) {
key = keys.pop();
object[key] = values.pop();
}
// Right
var keys = ['foo', 'bar'];
let values = [23, 42];
const object = {};
while (keys.length) {
var key = keys.pop();
object[key] = values.pop();
}
// Wrong
var admin_user = db.query('SELECT * FROM users ...');
// Right
var adminUser = db.query('SELECT * FROM users ...');
// Wrong
class bank_Account() {}
const bank_Account = (props) => {}
// Right
class BankAccount {}
const BankAccount = (props) => {}
// Wrong
const SECOND = 1 * 1000;
function File() {
}
File.fullPermissions = 0777;
// Right
var SECOND = 1 * 1000;
function File() {
}
File.FULL_PERMISSIONS = 0777;
// Wrong
var a = [
'hello', 'world'
];
var b = {"good": 'code'
, is generally: 'pretty'
};
// Right
var a = ['hello', 'world'];
var b = {
good: 'code',
'is generally': 'pretty',
};
// Wrong
var a = 0;
if (a == '') {
}
// Right
var a = 0;
if (a !== '') {
}
// Wrong
Array.prototype.empty = function() {
return !this.length;
}
var a = [];
if (a.empty()) {
}
// Right
var a = [];
if (!a.length) {
}
Any non-trivial conditions should be assigned to a descriptively named variable or function:
// Wrong
if (password.length >= 4 && /^(?=.*\d).{4,}$/.test(password)) {
}
// Right
var isValidPassword = password.length >= 4 && /^(?=.*\d).{4,}$/.test(password);
if (isValidPassword) {
}
To avoid deep nesting of if-statements, always return a function's value as early as possible.
// Wrong
function isPercentage(val) {
if (val >= 0) {
if (val < 100) {
return true;
} else {
return false;
}
} else {
return false;
}
}
// Right
function isPercentage(val) {
if (val < 0) {
return false;
}
if (val > 100) {
return false;
}
return true;
}
Or for this particular example it may also be fine to shorten things even further:
// Great
function isPercentage(val) {
var isInRange = (val >= 0 && val <= 100);
return isInRange;
}
Are are keeping this? I don't remember seeing any of our code using this rule.
Feel free to give your closures a name. It shows that you care about them, and will produce better stack traces, heap and cpu profiles.
// Wrong
req.on('end', function() {
});
// Right
req.on('end', function onEnd() {
});
Use closures, but avoid nesting them whenever possible.
// Wrong
setTimeout(() => {
client.connect(function() {
console.log('losing');
});
}, 1000);
// Right
function afterConnect() {
console.log('winning');
}
setTimeout(() => {
client.connect(afterConnect);
}, 1000);
- Core Principles
- Javascript
- CSS & SASS
- Liquid & HTML