Airbnb javascript style guide

I will pick some special rules and some rules i don’t think it is useful here

Objects

Rule 3.4: Define all the properties of an object in one place.

It is my common mistake. Don’t add properties to object once it defined. It is easy for other to miss the properties.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getKey(k) {
return `a key named ${k}`;
}

// bad
const obj = {
id: 5,
name: 'San Francisco',
};
obj[getKey('enabled')] = true;

// good
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};

Rule 3.8: Only quote properties that are invalid identifiers.

Airbnb think it is easier to read, improves syntax highlighting, and it is also more easily optimized by many JS engines.

1
2
3
4
5
6
7
8
9
10
11
12
13
// bad
const bad = {
'foo': 3,
'bar': 4,
'data-blah': 5,
};

// good
const good = {
foo: 3,
bar: 4,
'data-blah': 5,
};

This rule is more useful for client side javascript, beacuse server side javascript do not need to be minifed. For consistency of among object properties and between server side and client side code, I perfer to abolish this rule.

Rule 6.1 Use single quotes for strings

It is useful when we use double quote in json string and html.

Rule 7.1 Use function declarations instead of function expressions.

It is becuase function declarations are named, so they’re easier to identify in call stacks. A useful debuggin skill when dealing with callback.

Rule 7.3 Never declare a function in a non-function block (if, while, etc).

Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears.

Rule 7.6 Never use arguments, opt to use rest syntax ... instead.

It is becuase ... is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like like arguments.

Rule 7.7, 7.8, 7.12 and 7.13

They are:

  • Use default parameter syntax rather than mutating function arguments.
  • Avoid side effects with default parameters.
  • Never mutate parameters.
  • Never reassign parameters.

The idea is to keep the input parameter remain unchange and make the code have less unexpected behaviour.

Rule 9.3 Method can return this to help method chaining

For the functions do not have value to return, we can return this

Rule 9.4 toString() must have no side effects

It makes the code more difficult to debug, especially when we use console.log() to check the values.

Rule 10.5 Do not export mutable bindings.

Make the behaviour of function consistance.

Rule 11.1 Don’t use iterators

So we are easier to enforces the immutable rule

Rule 15.5 Use braces to create blocks in case and default clauses that contain lexical declarations

To prevent variable in different case mess up.

Rule 18.1 Use soft tabs set to 2 spaces.

I perfer to use 4 spaces, 2 spaces is too tight.

Rule 22.5 Don’t save references to this. Use arrow functions or Function#bind.

Reference