2016-06-09 02:09:53 +02:00
# JavaScript Style Guide
## Attribution
This JavaScript guide forked from the [node style guide ](https://github.com/felixge/node-style-guide ) created by [Felix Geisendörfer ](http://felixge.de/ ) and is
licensed under the [CC BY-SA 3.0 ](http://creativecommons.org/licenses/by-sa/3.0/ )
license.
2018-02-05 18:18:43 +01:00
## Prettier
We are gradually moving the Kibana code base over to Prettier.
Prettier is set up to run with ESLint, and to add new code paths to Prettier,
see `.eslintrc.js` in the root of the Kibana repo. This also means that if you
get ESLint errors related to Prettier, run `node scripts/eslint --fix` from the
root of the Kibana repo to fix these.
2016-06-09 02:09:53 +02:00
## 2 Spaces for indention
Use 2 spaces for indenting your code and swear an oath to never mix tabs and
spaces - a special kind of hell is awaiting you otherwise.
## Newlines
Use UNIX-style newlines (`\n`), and a newline character as the last character
of a file. Windows-style newlines (`\r\n`) are forbidden inside any repository.
## No trailing whitespace
Just like you brush your teeth after every meal, you clean up any trailing
whitespace in your JS files before committing. Otherwise the rotten smell of
careless neglect will eventually drive away contributors and/or co-workers.
## Use Semicolons
According to [scientific research][hnsemicolons], the usage of semicolons is
a core value of our community. Consider the points of [the opposition][], but
be a traditionalist when it comes to abusing error correction mechanisms for
cheap syntactic pleasures.
[the opposition]: http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding
[hnsemicolons]: http://news.ycombinator.com/item?id=1547647
2018-07-09 22:50:37 +02:00
## 100 characters per line
2016-06-09 02:09:53 +02:00
2018-07-09 22:50:37 +02:00
You should limit your lines to 100 chars. Prettier will check for that line width where enabled.
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
## Use `const` for variables
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
Your variable references should rarely be mutable, so use `const` for almost
everything. If you absolutely *must* mutate a reference, use `let` .
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
const foo = 'bar';
// if absolutely necessary, OK
let foo;
// bad
2016-06-09 02:09:53 +02:00
var foo = 'bar';
```
2016-11-02 02:22:59 +01:00
## Use single quotes for fixed strings
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
Use single quotes, unless you are writing JSON.
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
```js
// good
const foo = 'bar';
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
const foo = "bar";
```
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
## Use template strings to interpolate variables into strings
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
const foo = `Hello, ${name}` ;
// bad
const foo = 'Hello, ' + name;
2016-06-09 02:09:53 +02:00
```
2016-11-02 02:22:59 +01:00
## Use template strings to avoid escaping single quotes
Because readability is paramount.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
const foo = `You won't believe this.` ;
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
const foo = 'You won\'t believe this.';
2018-10-25 23:27:36 +02:00
const foo = "You won't believe this.";
2016-11-02 02:22:59 +01:00
```
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
## Use object destructuring
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
This helps avoid temporary references and helps prevent typo-related bugs.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// best
function fullName({ first, last }) {
return `${first} ${last}` ;
2016-06-09 02:09:53 +02:00
}
2016-11-02 02:22:59 +01:00
// good
function fullName(user) {
const { first, last } = user;
return `${first} ${last}` ;
}
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
function fullName(user) {
const first = user.first;
const last = user.last;
return `${first} ${last}` ;
}
2016-06-09 02:09:53 +02:00
```
2016-11-02 02:22:59 +01:00
## Use array destructuring
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
Directly accessing array values via index should be avoided, but if it is
necessary, use array destructuring:
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
const arr = [1, 2, 3];
// good
const [first, second] = arr;
// bad
const first = arr[0];
const second = arr[1];
2016-06-09 02:09:53 +02:00
```
2016-11-02 02:22:59 +01:00
## Opening braces go on the same line
Your opening braces go on the same line as the statement.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
if (true) {
console.log('winning');
}
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
if (true)
{
console.log('losing');
}
```
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
Also, notice the use of whitespace before and after the condition statement.
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
## Always use braces for conditionals and loops
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
if (err) {
return cb(err);
2016-06-09 02:09:53 +02:00
}
2016-11-02 02:22:59 +01:00
// bad
if (err) cb(err);
// bad
if (err)
return cb(err);
2016-06-09 02:09:53 +02:00
```
2016-11-02 02:22:59 +01:00
## Declare one variable per line, wherever it makes the most sense
This makes it easier to re-order the lines. However, ignore
[Crockford][crockfordconvention] when it comes to declaring variables deeper
inside a function, just put the declarations wherever they make sense.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
const keys = ['foo', 'bar'];
const values = [23, 42];
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
const keys = ['foo', 'bar'],
values = [23, 42];
2016-06-09 02:09:53 +02:00
```
[crockfordconvention]: http://javascript.crockford.com/code.html
## Use lowerCamelCase for variables, properties and function names
Variables, properties and function names should use `lowerCamelCase` . They
should also be descriptive. Single character variables and uncommon
abbreviations should generally be avoided.
```js
2016-11-02 02:22:59 +01:00
// good
const adminUser = getAdmin();
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
const admin_user = getAdmin();
2016-06-09 02:09:53 +02:00
```
2016-11-02 02:22:59 +01:00
## Use UpperCamelCase for class names (constructors)
2016-06-09 02:09:53 +02:00
Class names should be capitalized using `UpperCamelCase` .
```js
2016-11-02 02:22:59 +01:00
// good
class BankAccount {}
// bad
class bank_account {}
class bankAccount {}
2016-06-09 02:09:53 +02:00
```
2018-07-17 17:44:51 +02:00
## Prefix private class methods with an underscore
Identifying private class methods makes it easier to differentiate a class's public and internal
APIs, and makes private methods easier to mark as `private` when the code is migrated to TypeScript.
```js
// good
class BankAccount {
addFunds() {}
_calculateInterest() {}
}
```
2016-11-02 02:22:59 +01:00
## Magic numbers/strings
These are numbers (or other values) simply used in line in your code. *Do not
use these*, give them a variable name so they can be understood and changed
easily.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
const minWidth = 300;
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
if (width < minWidth ) {
...
}
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
if (width < 300 ) {
...
}
```
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
## Object properties and functions
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
Use object method shorthand syntax for functions on objects:
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
const foo = {
bar() {
...
}
};
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
const foo = {
bar: function () {
...
}
};
2016-06-09 02:09:53 +02:00
```
2016-11-02 02:22:59 +01:00
Use property value shorthand syntax for properties that share a name with a
variable. And put them at the beginning:
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
const bar = true;
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// good
const foo = {
bar
};
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
const foo = {
bar: bar
};
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// also bad (bar should be first)
const foo = {
baz: false,
bar
};
```
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
## Modules
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
Module dependencies should be written using native ES2015 syntax wherever
possible (which is almost everywhere):
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
import { mapValues } from 'lodash';
2017-01-12 19:29:04 +01:00
export mapValues;
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
const _ = require('lodash');
module.exports = _.mapValues;
// worse
define(['lodash'], function (_) {
2016-06-09 02:09:53 +02:00
...
2016-11-02 02:22:59 +01:00
});
2016-06-09 02:09:53 +02:00
```
2016-11-02 02:22:59 +01:00
In those extremely rare cases where you're writing server-side JavaScript in a
file that does not pass run through webpack, then use CommonJS modules.
In those even rarer cases where you're writing client-side code that does not
run through webpack, then do not use a module loader at all.
## Import only top-level modules
The files inside a module are implementation details of that module. They
should never be imported directly. Instead, you must only import the top-level
API that's exported by the module itself.
Without a clear mechanism in place in JS to encapsulate protected code, we make
a broad assumption that anything beyond the root of a module is an
implementation detail of that module.
On the other hand, a module should be able to import parent and sibling
modules.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
import foo from 'foo';
import child from './child';
import parent from '../';
import ancestor from '../../../';
import sibling from '../foo';
// bad
import inFoo from 'foo/child';
import inSibling from '../foo/child';
2016-06-09 02:09:53 +02:00
```
2017-01-12 19:29:04 +01:00
## Use named exports only
2017-01-12 19:30:04 +01:00
Favor named exports over default exports. See [#8641 ](https://github.com/elastic/kibana/issues/8641 ) for more background on this decision.
2017-01-12 19:29:04 +01:00
```js
// good
import { foo } from 'foo';
export foo;
// bad
import myDefaultModule from 'foo/child';
export default myDefaultModule;
```
2016-06-09 02:09:53 +02:00
## Global definitions
2016-11-02 02:22:59 +01:00
Don't do this. Everything should be wrapped in a module that can be depended on
by other modules. Even things as simple as a single value should be a module.
2016-06-09 02:09:53 +02:00
## Function definitions
2016-11-02 02:22:59 +01:00
Use function declarations over function expressions, so that their names will
show up in stack traces, making errors easier to debug.
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
Also, keep function definitions above other code instead of relying on function
hoisting.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
2016-06-09 02:09:53 +02:00
function myFunc() {
...
}
2016-11-02 02:22:59 +01:00
// bad
const myFunc = function () {
...
};
2016-06-09 02:09:53 +02:00
```
2016-11-02 02:22:59 +01:00
## Arrow functions
If you must use a function expression, then use an arrow function:
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
[1, 2, 3].map((n) => {
const m = doSomething(n);
return m - n;
});
// bad
[1, 2, 3].map(function (n) {
const m = doSomething(n);
return m - n;
});
```
If your function body does not include braces and only accepts one argument,
2018-06-27 05:17:41 +02:00
then omit the argument parentheses:
2016-11-02 02:22:59 +01:00
```js
// good
[1, 2, 3].map(n => n + 1);
// bad
[1, 2, 3].map((n) => n + 1);
// bad
[1, 2, 3].map(n => {
return n + 1;
});
```
If your arrow function is only returning an object literal, then wrap the
2018-06-27 05:17:41 +02:00
object in parentheses rather than using an explicit return:
2016-11-02 02:22:59 +01:00
```js
// good
() => ({
foo: 'bar'
})
// bad
() => {
return {
foo: 'bar'
};
}
2016-06-09 02:09:53 +02:00
```
## Object / Array creation
Use trailing commas and put *short* declarations on a single line. Only quote
keys when your interpreter complains:
```js
2016-11-02 02:22:59 +01:00
// good
const a = ['hello', 'world'];
const b = {
2016-06-09 02:09:53 +02:00
good: 'code',
'is generally': 'pretty'
};
2016-11-02 02:22:59 +01:00
// bad
const a = [
2016-06-09 02:09:53 +02:00
'hello', 'world'
];
2016-11-02 02:22:59 +01:00
const b = {'good': 'code'
2016-06-09 02:09:53 +02:00
, is generally: 'pretty'
};
```
## Object / Array iterations, transformations and operations
2016-11-02 02:22:59 +01:00
Use native methods to iterate and transform arrays and objects where possible.
Avoid `for` and `while` loops as they introduce the possibility of infinite
loops and break out of our preferred convention of declarative programming.
2016-06-09 02:09:53 +02:00
Use descriptive variable names in the closures.
2016-11-02 02:22:59 +01:00
Use a utility library as needed and where it will make code more
comprehensible.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// best
const userNames = users.map(user => user.name);
// ok
import { pluck } from 'lodash';
const userNames = pluck(users, 'name');
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
const userNames = [];
for (let i = 0; i < users.length ; i + + ) {
userNames.push(users[i].name);
}
2016-06-09 02:09:53 +02:00
```
2016-11-02 02:22:59 +01:00
## Use the spread operator (...) for copying arrays
This helps with expressiveness and readability.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
const arr = [1, 2, 3];
// good
const arrCopy = [...arr];
// bad
const arrCopy = arr.slice();
2016-06-09 02:09:53 +02:00
```
## Use the === operator
Programming is not about remembering [stupid rules][comparisonoperators]. Use
the triple equality operator as it will work just as expected.
```js
2016-11-02 02:22:59 +01:00
const a = 0;
// good
2016-06-09 02:09:53 +02:00
if (a !== '') {
console.log('winning');
}
2016-11-02 02:22:59 +01:00
// bad
2016-06-09 02:09:53 +02:00
if (a == '') {
console.log('losing');
}
```
[comparisonoperators]: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators
## Only use ternary operators for small, simple code
2016-11-02 02:22:59 +01:00
And *never* use multiple ternaries together, because they make it more
difficult to reason about how different values flow through the conditions
involved. Instead, structure the logic for maximum readability.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good, a situation where only 1 ternary is needed
const foo = (a === b) ? 1 : 2;
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
const foo = (a === b) ? 1 : (a === c) ? 2 : 3;
2016-06-09 02:09:53 +02:00
```
## Do not extend built-in prototypes
Do not extend the prototype of native JavaScript objects. Your future self will
be forever grateful.
```js
2016-11-02 02:22:59 +01:00
// bad
Array.prototype.empty = function () {
2016-06-09 02:09:53 +02:00
return !this.length;
}
```
## Use descriptive conditions
2016-11-02 02:22:59 +01:00
Any non-trivial conditions should be converted to functions or assigned to
descriptively named variables. By breaking up logic into smaller,
self-contained blocks, it becomes easier to reason about the higher-level
logic. Additionally, these blocks become good candidates for extraction into
their own modules, with unit-tests.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// best
function isShape(thing) {
return thing instanceof Shape;
}
function notSquare(thing) {
return !(thing instanceof Square);
}
if (isShape(thing) & & notSquare(thing)) {
...
2016-06-09 02:09:53 +02:00
}
2016-11-02 02:22:59 +01:00
// good
const isShape = thing instanceof Shape;
const notSquare = !(thing instanceof Square);
if (isShape & & notSquare) {
...
}
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
if (thing instanceof Shape & & !(thing instanceof Square)) {
...
2016-06-09 02:09:53 +02:00
}
```
## Name regular expressions
```js
2016-11-02 02:22:59 +01:00
// good
const validPassword = /^(?=.*\d).{4,}$/;
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
if (password.length >= 4 & & validPassword.test(password)) {
2016-06-09 02:09:53 +02:00
console.log('password is valid');
}
2016-11-02 02:22:59 +01:00
// bad
2016-06-09 02:09:53 +02:00
if (password.length >= 4 && /^(?=.*\d).{4,}$/.test(password)) {
console.log('losing');
}
```
## Write small functions
Keep your functions short. A good function fits on a slide that the people in
the last row of a big room can comfortably read. So don't count on them having
perfect vision and limit yourself to ~15 lines of code per function.
2016-11-02 02:22:59 +01:00
## Use "rest" syntax rather than built-in `arguments`
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
For expressiveness sake, and so you can be mix dynamic and explicit arguments.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
function something(foo, ...args) {
...
}
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
function something(foo) {
const args = Array.from(arguments).slice(1);
...
2016-06-09 02:09:53 +02:00
}
```
2016-11-02 02:22:59 +01:00
## Default argument syntax
Always use the default argument syntax for optional arguments.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
function foo(options = {}) {
...
}
// bad
function foo(options) {
if (typeof options === 'undefined') {
options = {};
2016-06-09 02:09:53 +02:00
}
2016-11-02 02:22:59 +01:00
...
2016-06-09 02:09:53 +02:00
}
```
2016-11-02 02:22:59 +01:00
And put your optional arguments at the end.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
function foo(bar, options = {}) {
...
2016-06-09 02:09:53 +02:00
}
2016-11-02 02:22:59 +01:00
// bad
function foo(options = {}, bar) {
...
}
```
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
## Return/throw early from functions
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
To avoid deep nesting of if-statements, always return a function's value as early
as possible. And where possible, do any assertions first:
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
function doStuff(val) {
if (val > 100) {
throw new Error('Too big');
}
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
if (val < 0 ) {
return false;
}
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// ... stuff
}
// bad
function doStuff(val) {
if (val >= 0) {
if (val < 100 ) {
// ... stuff
} else {
throw new Error('Too big');
}
} else {
return false;
}
}
2016-06-09 02:09:53 +02:00
```
2016-11-02 02:22:59 +01:00
## Chaining operations
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
When using a chaining syntax, indent the subsequent chained operations.
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
Also, if the chain is long, each method should be on a new line.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
2016-06-09 02:09:53 +02:00
$http.get('/info')
2018-06-27 05:17:41 +02:00
.then(({ data }) => this.transformInfo(data))
2016-06-09 02:09:53 +02:00
.then((transformed) => $http.post('/new-info', transformed))
.then(({ data }) => console.log(data));
2016-11-02 02:22:59 +01:00
// bad
$http.get('/info')
2018-06-27 05:17:41 +02:00
.then(({ data }) => this.transformInfo(data))
2016-11-02 02:22:59 +01:00
.then((transformed) => $http.post('/new-info', transformed))
.then(({ data }) => console.log(data));
```
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
## Avoid mutability and state
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
Wherever possible, do not rely on mutable state. This means you should not
reassign variables, modify object properties, or push values to arrays.
Instead, create new variables, and shallow copies of objects and arrays:
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
function addBar(foos, foo) {
const newFoo = {...foo, name: 'bar'};
return [...foos, newFoo];
}
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
function addBar(foos, foo) {
foo.name = 'bar';
foos.push(foo);
}
2016-06-09 02:09:53 +02:00
```
2016-11-02 02:22:59 +01:00
## Use thunks to create closures, where possible
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
For trivial examples (like the one that follows), thunks will seem like
overkill, but they encourage isolating the implementation details of a closure
from the business logic of the calling code.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
function connectHandler(client, callback) {
return () => client.connect(callback);
2016-06-09 02:09:53 +02:00
}
2016-11-02 02:22:59 +01:00
setTimeout(connectHandler(client, afterConnect), 1000);
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// not as good
setTimeout(() => {
client.connect(afterConnect);
}, 1000);
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
setTimeout(() => {
client.connect(() => {
...
2016-06-09 02:09:53 +02:00
});
}, 1000);
```
## Use slashes for comments
Use slashes for both single line and multi line comments. Try to write
comments that explain higher level mechanisms or clarify difficult
2016-11-02 02:22:59 +01:00
segments of your code. *Don't use comments to restate trivial things* .
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
*Exception:* Comment blocks describing a function and its arguments
(docblock) should start with `/**` , contain a single `*` at the beginning of
each line, and end with `*/` .
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
2016-06-09 02:09:53 +02:00
// 'ID_SOMETHING=VALUE' -> ['ID_SOMETHING=VALUE', 'SOMETHING', 'VALUE']
2016-11-02 02:22:59 +01:00
const matches = item.match(/ID_([^\n]+)=([^\n]+)/));
2016-06-09 02:09:53 +02:00
/**
* Fetches a user from...
* @param {string} id - id of the user
* @return {Promise}
*/
function loadUser(id) {
// This function has a nasty side effect where a failure to increment a
// redis counter used for statistics will cause an exception. This needs
// to be fixed in a later iteration.
...
}
2016-11-02 02:22:59 +01:00
const isSessionValid = (session.expires < Date.now ( ) ) ;
2016-06-09 02:09:53 +02:00
if (isSessionValid) {
...
}
2016-11-02 02:22:59 +01:00
// bad
2016-06-09 02:09:53 +02:00
// Execute a regex
2016-11-02 02:22:59 +01:00
const matches = item.match(/ID_([^\n]+)=([^\n]+)/));
2016-06-09 02:09:53 +02:00
// Usage: loadUser(5, function() { ... })
function loadUser(id, cb) {
// ...
}
// Check if the session is valid
2016-11-02 02:22:59 +01:00
const isSessionValid = (session.expires < Date.now ( ) ) ;
2016-06-09 02:09:53 +02:00
// If the session is valid
if (isSessionValid) {
2016-11-02 02:22:59 +01:00
...
2016-06-09 02:09:53 +02:00
}
```
## Do not comment out code
2016-11-02 02:22:59 +01:00
We use a version management system. If a line of code is no longer needed,
remove it, don't simply comment it out.
2016-06-09 02:09:53 +02:00
## Classes/Constructors and Inheritance
2016-11-02 02:22:59 +01:00
If you must use a constructor, then use the native `class` syntax. *Never* use
third party "class" utilities, and never mutate prototypes.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// best (no local state at all)
function addUser(users, user) {
return [...users, user];
2016-06-09 02:09:53 +02:00
}
2016-11-02 02:22:59 +01:00
const users = addUser([], { name: 'foo' });
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// good
class Users {
add(user) {
...
}
2016-06-09 02:09:53 +02:00
}
2016-11-02 02:22:59 +01:00
const users = new Users();
users.add({ name: 'foo' });
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
// bad
function Users() {
2016-06-09 02:09:53 +02:00
...
}
2016-11-02 02:22:59 +01:00
Users.prototype.add = function () {
2016-06-09 02:09:53 +02:00
...
2016-11-02 02:22:59 +01:00
};
const users = new Users();
users.add({ name: 'foo' });
2016-06-09 02:09:53 +02:00
```
2016-11-02 02:22:59 +01:00
## Do not alias `this`
2016-06-09 02:09:53 +02:00
2016-11-02 02:22:59 +01:00
Try not to rely on `this` at all, but if you must, then use arrow functions
instead of aliasing it.
2016-06-09 02:09:53 +02:00
```js
2016-11-02 02:22:59 +01:00
// good
class Users {
add(user) {
return createUser(user)
.then(response => this.users.push(response.user));
}
2016-06-09 02:09:53 +02:00
}
2016-11-02 02:22:59 +01:00
// bad
class Users {
add(user) {
const self = this;
return createUser(user).then(function (response) {
self.users.push(response.user);
});
}
2016-06-09 02:09:53 +02:00
}
```
## Getters and Setters
Feel free to use getters that are free from [side effects][sideeffect], like
providing a length property for a collection class.
2016-11-02 02:22:59 +01:00
Do not use setters, they cause more problems than they can solve.
2016-06-09 02:09:53 +02:00
[sideeffect]: http://en.wikipedia.org/wiki/Side_effect_(computer_science)