Coding Guidelines

Consistency is key

Most projects are not built or maintained by a single person. Instead, there is a collection of people involved, who all have their own personal preferences. If everyone would use their personal style, maintainability would suffer.

With coding guidelines enforced, the code will be easier to understand. With understandability comes readability, changeability, extensibility and maintainability.

Variable assignment

Prefer const over let. Only use let to indicate that a variable will be reassigned. Never use var.

// Good
const person = { name: 'Luigi' };
person.name = 'Luigi';

// Bad, the variable was never reassigned
let person = { name: 'Mario' };
person.name = 'Mario';

Variable names

Variable names generally shouldn't be abbreviated.

// Good
function saveUser(user) {
    localStorage.set('user', user);
}

// Bad, it's hard to reason about abbreviations in blocks as they grow.
function saveUser(u) {
    localStorage.set('user', u);
}

String Interpolation

When embedding expressions, always use the template literals syntax.

// Good
const name = 'Luigi';

console.log(`Hello, $(name)!`); // Result: Hello, Luigi!

// Bad
const one = 1;
const two = 2;

console.log("The sum of one and two is " + (one + two)); // Result: The sum of one and two is 3

Comparisons

Always use a triple equal to do variable comparisons. If you're unsure of the type, cast it first.

// Good
const one = 1;
const another = "1";

if (one === parseInt(another)) {
    // ...
}

// Bad
const one = 1;
const another = "1";

if (one == another) {
    // ...
}

If statements

Always use curly brackets.

// Good
if (condition) {
   ...
}

// Bad
if (condition) ...

Happy path

Generally a function should have its unhappy path first and its happy path last. In most cases this will cause the happy path being in an unindented part of the function which makes it more readable.

// Good

if (! goodCondition) {
  throw 'Some error message here!';
}

// do work
// Bad

if (goodCondition) {
 // do work
}

throw 'Some error message here!';