Whitespace
Indentation
Use soft tabs set to 2 spaces. eslint: indent
// bad
function foo() {
let name;
}
// bad
function bar() {
let name;
}
// good
function baz() {
let name;
}
Space before blocks
Place 1 space before the leading brace. eslint: space-before-blocks
// bad
function test(){
console.log('test');
}
// good
function test() {
console.log('test');
}
// bad
dog.set('attr',{
age: '1 year',
breed: 'Bernese Mountain Dog',
});
// good
dog.set('attr', {
age: '1 year',
breed: 'Bernese Mountain Dog',
});
Space around keywords
Place 1 space before the opening parenthesis in control statements (if, while, etc.). Place no space between the argument list and the function name in function calls and declarations. eslint: keyword-spacing
// bad
if(isJedi) {
fight ();
}
// good
if (isJedi) {
fight();
}
// bad
function fight () {
console.log ('Swooosh!');
}
// good
function fight() {
console.log('Swooosh!');
}
Space around operators
Set off operators with spaces. eslint: space-infix-ops
// bad
const x=y+5;
// good
const x = y + 5;
Space inside curly braces
Add spaces inside curly braces. eslint: object-curly-spacing
// bad
const foo = {clark: 'kent'};
// good
const foo = { clark: 'kent' };
Do not add spaces inside parentheses (space-in-parens) or array brackets (array-bracket-spacing).
// bad — parentheses
function bar( foo ) {
return foo;
}
// good
function bar(foo) {
return foo;
}
// bad — brackets
const foo = [ 1, 2, 3 ];
console.log(foo[ 0 ]);
// good
const foo = [1, 2, 3];
console.log(foo[0]);
End of file
End files with a single newline character. eslint: eol-last
Blank lines
Leave a blank line after blocks and before the next statement.
// bad
if (foo) {
return bar;
}
return baz;
// good
if (foo) {
return bar;
}
return baz;
Do not pad blocks with blank lines. eslint: padded-blocks
// bad
function bar() {
console.log(foo);
}
// good
function bar() {
console.log(foo);
}
Do not use multiple blank lines to pad your code. eslint: no-multiple-empty-lines
Chained method calls
Use indentation when making long method chains (more than 2 method chains). Use a leading dot to emphasize that the line is a method call, not a new statement. eslint: newline-per-chained-call, no-whitespace-before-property
// bad
$('#items').find('.selected').highlight().end().find('.open').updateCount();
// bad
$('#items').
find('.selected').
highlight().
end().
find('.open').
updateCount();
// good
$('#items')
.find('.selected')
.highlight()
.end()
.find('.open')
.updateCount();
Line length
Avoid lines longer than 100 characters (including whitespace). Long strings are exempt. eslint: max-len
// bad
const foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy;
// good
const foo = jsonData
&& jsonData.foo
&& jsonData.foo.bar
&& jsonData.foo.bar.baz
&& jsonData.foo.bar.baz.quux
&& jsonData.foo.bar.baz.quux.xyzzy;
// better
const foo = jsonData
?.foo
?.bar
?.baz
?.quux
?.xyzzy;
Additional spacing rules
| Rule | ESLint |
|---|
| Space after commas, not before | comma-spacing |
| Space inside open/close block tokens on one-liners | block-spacing |
| Space after colon in object properties, not before | key-spacing |
| No spaces inside computed property brackets | computed-property-spacing |
| No space between function name and invocation | func-call-spacing |
| No trailing spaces at end of lines | no-trailing-spaces |
Commas
No leading commas
eslint: comma-style
// bad
const story = [
once
, upon
, aTime
];
// good
const story = [
once,
upon,
aTime,
];
// bad
const hero = {
firstName: 'Ada'
, lastName: 'Lovelace'
, birthYear: 1815
};
// good
const hero = {
firstName: 'Ada',
lastName: 'Lovelace',
birthYear: 1815,
};
Trailing commas
Always use trailing commas. eslint: comma-dangle
Trailing commas lead to cleaner git diffs. Transpilers like Babel remove them from the transpiled output, so there are no legacy browser concerns.
// bad
const hero = {
firstName: 'Dana',
lastName: 'Scully'
};
const heroes = [
'Batman',
'Superman'
];
// good
const hero = {
firstName: 'Dana',
lastName: 'Scully',
};
const heroes = [
'Batman',
'Superman',
];
Trailing commas also apply to function parameters and arguments:
// bad
function createHero(
firstName,
lastName,
inventorOf
) {
// does nothing
}
// good
function createHero(
firstName,
lastName,
inventorOf,
) {
// does nothing
}
// good (note that a comma must not appear after a "rest" element)
function createHero(
firstName,
lastName,
inventorOf,
...heroArgs
) {
// does nothing
}
Semicolons
Always use semicolons. eslint: semi
JavaScript’s Automatic Semicolon Insertion (ASI) contains eccentric behaviors that can cause your code to break in non-obvious ways. Always terminate statements explicitly.
// bad - raises exception
const luke = {}
const leia = {}
[luke, leia].forEach((jedi) => jedi.father = 'vader')
// bad - raises exception
const reaction = "No! That's impossible!"
(async function meanwhileOnTheFalcon() {
// ...
}())
// bad - returns `undefined` instead of the value on the next line
// because ASI kicks in when `return` is on a line by itself
function foo() {
return
'search your feelings, you know it to be foo'
}
// good
const luke = {};
const leia = {};
[luke, leia].forEach((jedi) => {
jedi.father = 'vader';
});
// good
const reaction = "No! That's impossible!";
(async function meanwhileOnTheFalcon() {
// ...
}());
// good
function foo() {
return 'search your feelings, you know it to be foo';
}
Type Casting & Coercion
Perform type coercion at the beginning of the statement.
Strings
eslint: no-new-wrappers
// => this.reviewScore = 9;
// bad
const totalScore = new String(this.reviewScore); // typeof totalScore is "object" not "string"
// bad
const totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf()
// bad
const totalScore = this.reviewScore.toString(); // isn't guaranteed to return a string
// good
const totalScore = String(this.reviewScore);
Numbers
Use Number for type casting and parseInt always with a radix for parsing strings. eslint: radix, no-new-wrappers
const inputValue = '4';
// bad
const val = new Number(inputValue);
// bad
const val = +inputValue;
// bad
const val = inputValue >> 0;
// bad
const val = parseInt(inputValue);
// good
const val = Number(inputValue);
// good
const val = parseInt(inputValue, 10);
If you must use bitshift for performance reasons, leave a comment explaining why. Also be aware that bitshift operations always return a 32-bit integer — values larger than 2,147,483,647 will overflow.
// good
/**
* parseInt was the reason my code was slow.
* Bitshifting the String to coerce it to a
* Number made it a lot faster.
*/
const val = inputValue >> 0;
Booleans
eslint: no-new-wrappers
const age = 0;
// bad
const hasAge = new Boolean(age);
// good
const hasAge = Boolean(age);
// best
const hasAge = !!age;