function example() {
superPower(); // => Flying
@@ -1249,17 +1692,23 @@ superPower = new ⬆ back to top
-Comparison Operators & Equality
+Comparison Operators & Equality
+
+
-
-15.1 Use
=== and !== over == and !=.
--
-
15.2 Conditional statements such as the if statement evaluate their expression using coercion with the ToBoolean abstract method and always follow these simple rules:
+15.1 Use === and !== over == and !=. eslint: eqeqeq
-eslint rules: eqeqeq.
+
+
+-
+
15.2 Conditional statements such as the if statement evaluate their expression using coercion with the ToBoolean abstract method and always follow these simple rules:
+
+
+-
+Objects evaluate to true
-Objects evaluate to true
-
Undefined evaluates to false
@@ -1273,15 +1722,19 @@ superPower = new Numbers evaluate to false if +0, -0, or NaN, otherwise true
-
-
Strings evaluate to false if an empty string '', otherwise true
+Strings evaluate to false if an empty string '', otherwise true
+
+
-if ([0]) {
+if ([0] && []) {
// true
- // An array is an object, objects evaluate to true
+ // an array (even an empty one) is an object, objects will evaluate to true
}
+
+
-15.3 Use shortcuts.
+15.3 Use shortcuts.
// bad
if (name !== '') {
@@ -1302,18 +1755,113 @@ superPower = new if (collection.length) {
// ...stuff...
}
+
+
+
+
+15.4 For more information see Truth Equality and JavaScript by Angus Croll.
+
+
+
+
+15.5 Use braces to create blocks in case and default clauses that contain lexical declarations (e.g. let, const, function, and class).
+
+
+Why? Lexical declarations are visible in the entire switch block but only get initialized when assigned, which only happens when its case is reached. This causes problems when multiple case clauses attempt to define the same thing.
+
+
+eslint rules: no-case-declarations.
+
+ // bad
+ switch (foo) {
+ case 1:
+ let x = 1;
+ break;
+ case 2:
+ const y = 2;
+ break;
+ case 3:
+ function f() {}
+ break;
+ default:
+ class C {}
+ }
+
+ // good
+ switch (foo) {
+ case 1: {
+ let x = 1;
+ break;
+ }
+ case 2: {
+ const y = 2;
+ break;
+ }
+ case 3: {
+ function f() {}
+ break;
+ }
+ case 4:
+ bar();
+ break;
+ default: {
+ class C {}
+ }
+ }
+
+
+
+
+15.6 Ternaries should not be nested and generally be single line expressions.
+
+eslint rules: no-nested-ternary.
+
+// bad
+const foo = maybe1 > maybe2
+ ? "bar"
+ : value1 > value2 ? "baz" : null;
+
+// better
+const maybeNull = value1 > value2 ? 'baz' : null;
+
+const foo = maybe1 > maybe2
+ ? 'bar'
+ : maybeNull;
+
+// best
+const maybeNull = value1 > value2 ? 'baz' : null;
+
+const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
+
+
+
+
+15.7 Avoid unneeded ternary statements.
+
+eslint rules: no-unneeded-ternary.
+
+// bad
+const foo = a ? a : b;
+const bar = c ? true : false;
+const baz = c ? false : true;
+
+// good
+const foo = a || b;
+const bar = !!c;
+const baz = !c;
-
15.4 For more information see Truth Equality and JavaScript by Angus Croll.
⬆ back to top
-Blocks
+
Blocks
+
+
-
-
16.1 Use braces with all multi-line blocks.
+16.1 Use braces with all multi-line blocks.
// bad
if (test)
@@ -1328,18 +1876,17 @@ superPower = new // bad
-function () { return false; }
+function foo() { return false; }
// good
-function () {
+function bar() {
return false;
}
+
+
-
-
16.2 If you're using multi-line blocks with if and else, put else on the same line as your
-if block's closing brace.
-
-eslint rules: brace-style.
+16.2 If you're using multi-line blocks with if and else, put else on the same line as your if block's closing brace. eslint: brace-style jscs: disallowNewlineBeforeBlockStatements
// bad
if (test) {
@@ -1363,11 +1910,13 @@ superPower = new ⬆ back to top
-Comments
+Comments
+
+
-
-
17.1 Use /** ... */ for multi-line comments. Include a description, specify types and values for all parameters and return values.
+17.1 Use /** ... */ for multi-line comments. Include a description, specify types and values for all parameters and return values.
// bad
// make() returns a new element
@@ -1387,8 +1936,8 @@ superPower = new * make() returns a new element
* based on the passed in tag name
*
- * @param {String} tag
- * @return {Element} element
+ * @param {String} tag
+ * @return {Element} element
*/
function make(tag) {
@@ -1396,9 +1945,11 @@ superPower = new return element;
}
+
+
-
-
17.2 Use // for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it's on the first line of a block.
+17.2 Use // for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it's on the first line of a block.
// bad
const active = true; // is current tab
@@ -1433,12 +1984,18 @@ superPower = new return type;
}
-
-17.3 Prefixing your comments with FIXME or TODO helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are FIXME -- need to figure this out or TODO -- need to implement.
--
-
17.4 Use // FIXME: to annotate problems.
-class Calculator extends Abacus {
+
+
+-
+
17.3 Prefixing your comments with FIXME or TODO helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are FIXME: -- need to figure this out or TODO: -- need to implement.
+
+
+
+
-
+
17.4 Use // FIXME: to annotate problems.
+
+class Calculator extends Abacus {
constructor() {
super();
@@ -1446,11 +2003,13 @@ superPower = new = 0;
}
}
+
+
-
-
17.5 Use // TODO: to annotate solutions to problems.
+17.5 Use // TODO: to annotate solutions to problems.
-class Calculator extends Abacus {
+class Calculator extends Abacus {
constructor() {
super();
@@ -1464,124 +2023,128 @@ superPower = new ⬆ back to top
-Whitespace
+Whitespace
+
+
-
-
18.1 Use soft tabs set to 2 spaces.
-
-eslint rules: indent.
-
- // bad
- function () {
- ∙∙∙∙const name;
- }
-
- // bad
- function () {
- ∙const name;
- }
-
- // good
- function () {
- ∙∙const name;
- }
-
--
-
18.2 Place 1 space before the leading brace.
-
-eslint rules: 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',
- });
-
--
-
18.3 Place 1 space before the opening parenthesis in control statements (if, while etc.). Place no space before the argument list in function calls and declarations.
-
-eslint rules: space-after-keywords, space-before-keywords.
-
- // bad
- if(isJedi) {
- fight ();
- }
-
- // good
- if (isJedi) {
- fight();
- }
-
- // bad
- function fight () {
- console.log ('Swooosh!');
- }
-
- // good
- function fight() {
- console.log('Swooosh!');
- }
-
--
-
18.4 Set off operators with spaces.
-
-eslint rules: space-infix-ops.
-
- // bad
- const x=y+5;
-
- // good
- const x = y + 5;
-
--
-
18.5 End files with a single newline character.
+18.1 Use soft tabs set to 2 spaces. eslint: indent jscs: validateIndentation
// bad
-(function (global) {
+function foo() {
+∙∙∙∙const name;
+}
+
+// bad
+function bar() {
+∙const name;
+}
+
+// good
+function baz() {
+∙∙const name;
+}
+
+
+
+-
+
18.2 Place 1 space before the leading brace. eslint: space-before-blocks jscs: requireSpaceBeforeBlockStatements
+
+// 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',
+});
+
+
+
+-
+
18.3 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 jscs: requireSpaceAfterKeywords
+
+// bad
+if(isJedi) {
+ fight ();
+}
+
+// good
+if (isJedi) {
+ fight();
+}
+
+// bad
+function fight () {
+ console.log ('Swooosh!');
+}
+
+// good
+function fight() {
+ console.log('Swooosh!');
+}
+
+
+
+-
+
18.4 Set off operators with spaces. eslint: space-infix-ops jscs: requireSpaceBeforeBinaryOperators, requireSpaceAfterBinaryOperators
+
+// bad
+const x=y+5;
+
+// good
+const x = y + 5;
+
+
+
+-
+
18.5 End files with a single newline character.
+
+// bad
+(function (global) {
// ...stuff...
})(this);
// bad
-(function (global) {
+(function (global) {
// ...stuff...
})(this);↵
↵
// good
-(function (global) {
+(function (global) {
// ...stuff...
})(this);↵
+
+
-
-
18.6 Use indentation when making long method chains. Use a leading dot, which
-emphasizes that the line is a method call, not a new statement.
+18.6 Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which
+emphasizes 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').
+ find('.selected').
highlight().
end().
- find('.open').
+ find('.open').
updateCount();
// good
@@ -1593,7 +2156,7 @@ emphasizes that the line is a method call, not a new statement.
.updateCount();
// bad
-const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').class('led', true)
+const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true)
.attr('width', (radius + margin) * 2).append('svg:g')
.attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
.call(tron.led);
@@ -1606,10 +2169,15 @@ emphasizes that the line is a method call, not a new statement.
.attr('width', (radius + margin) * 2)
.append('svg:g')
.attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
- .call(tron.led);
+ .call(tron.led);
+
+// good
+const leds = stage.selectAll('.led').data(data);
+
+
-
-
18.7 Leave a blank line after blocks and before the next statement.
+18.7 Leave a blank line after blocks and before the next statement. jscs: requirePaddingNewLinesAfterBlocks
// bad
if (foo) {
@@ -1663,208 +2231,236 @@ emphasizes that the line is a method call, not a new statement.
];
return arr;
+
+
-
-
18.8 Do not pad your blocks with blank lines.
+18.8 Do not pad your blocks with blank lines. eslint: padded-blocks jscs: disallowPaddingNewlinesInBlocks
-eslint rules: padded-blocks.
+// bad
+function bar() {
- // bad
- function bar() {
+ console.log(foo);
- console.log(foo);
+}
- }
+// also bad
+if (baz) {
- // also bad
- if (baz) {
+ console.log(qux);
+} else {
+ console.log(foo);
- console.log(qux);
- } else {
- console.log(foo);
+}
- }
+// good
+function bar() {
+ console.log(foo);
+}
- // good
- function bar() {
- console.log(foo);
- }
+// good
+if (baz) {
+ console.log(qux);
+} else {
+ console.log(foo);
+}
- // good
- if (baz) {
- console.log(qux);
- } else {
- console.log(foo);
- }
+
-
-
18.9 Do not add spaces inside parentheses.
+18.9 Do not add spaces inside parentheses. eslint: space-in-parens jscs: disallowSpacesInsideParentheses
-eslint rules: space-in-parens.
+// bad
+function bar( foo ) {
+ return foo;
+}
- // bad
- function bar( foo ) {
- return foo;
- }
+// good
+function bar(foo) {
+ return foo;
+}
- // good
- function bar(foo) {
- return foo;
- }
+// bad
+if ( foo ) {
+ console.log(foo);
+}
- // bad
- if ( foo ) {
- console.log(foo);
- }
+// good
+if (foo) {
+ console.log(foo);
+}
- // good
- if (foo) {
- console.log(foo);
- }
+
-
-
18.10 Do not add spaces inside brackets.
+18.10 Do not add spaces inside brackets. eslint: array-bracket-spacing jscs: disallowSpacesInsideArrayBrackets
-eslint rules: array-bracket-spacing.
+// bad
+const foo = [ 1, 2, 3 ];
+console.log(foo[ 0 ]);
- // bad
- const foo = [ 1, 2, 3 ];
- console.log(foo[ 0 ]);
+// good
+const foo = [1, 2, 3];
+console.log(foo[0]);
- // good
- const foo = [1, 2, 3];
- console.log(foo[0]);
+
-
-
18.11 Add spaces inside curly braces.
+18.11 Add spaces inside curly braces. eslint: object-curly-spacing jscs: requireSpacesInsideObjectBrackets
-eslint rules: object-curly-spacing.
+// bad
+const foo = {clark: 'kent'};
- // bad
- const foo = {clark: 'kent'};
+// good
+const foo = { clark: 'kent' };
- // good
- const foo = { clark: 'kent' };
+
+
+
-
+
18.12 Avoid having lines of code that are longer than 100 characters (including whitespace). eslint: max-len jscs: maximumLineLength
+
+
+Why? This ensures readability and maintainability.
+
+
+// bad
+const foo = 'Whatever national crop flips the window. The cartoon reverts within the screw. Whatever wizard constrains a helpful ally. The counterpart ascends!';
+
+// bad
+$.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.'));
+
+// good
+const foo = 'Whatever national crop flips the window. The cartoon reverts within the screw. ' +
+ 'Whatever wizard constrains a helpful ally. The counterpart ascends!';
+
+// good
+$.ajax({
+ method: 'POST',
+ url: 'https://airbnb.com/',
+ data: { name: 'John' },
+})
+ .done(() => console.log('Congratulations!'))
+ .fail(() => console.log('You have failed this city.'));
⬆ back to top
-Commas
+
Commas
+
+
-
-
19.1 Leading commas: Nope.
+19.1 Leading commas: Nope. eslint: comma-style jscs: requireCommaBeforeLineBreak
-eslint rules: comma-style.
+// bad
+const story = [
+ once
+ , upon
+ , aTime
+];
- // bad
- const story = [
- once
- , upon
- , aTime
- ];
+// good
+const story = [
+ once,
+ upon,
+ aTime,
+];
- // good
- const story = [
- once,
- upon,
- aTime,
- ];
+// bad
+const hero = {
+ firstName: 'Ada'
+ , lastName: 'Lovelace'
+ , birthYear: 1815
+ , superPower: 'computers'
+};
- // bad
- const hero = {
- firstName: 'Ada'
- , lastName: 'Lovelace'
- , birthYear: 1815
- , superPower: 'computers'
- };
+// good
+const hero = {
+ firstName: 'Ada',
+ lastName: 'Lovelace',
+ birthYear: 1815,
+ superPower: 'computers',
+};
- // good
- const hero = {
- firstName: 'Ada',
- lastName: 'Lovelace',
- birthYear: 1815,
- superPower: 'computers',
- };
+
-
-
19.2 Additional trailing comma: Yup.
-
-eslint rules: no-comma-dangle.
+19.2 Additional trailing comma: Yup. eslint: comma-dangle jscs: requireTrailingComma
Why? This leads to cleaner git diffs. Also, transpilers like Babel will remove the additional trailing comma in the transpiled code which means you don't have to worry about the trailing comma problem in legacy browsers.
- // bad - git diff without trailing comma
- const hero = {
- firstName: 'Florence',
- - lastName: 'Nightingale'
- + lastName: 'Nightingale',
- + inventorOf: ['coxcomb graph', 'modern nursing']
- };
+// bad - git diff without trailing comma
+const hero = {
+ firstName: 'Florence',
+- lastName: 'Nightingale'
++ lastName: 'Nightingale',
++ inventorOf: ['coxcomb graph', 'modern nursing']
+};
- // good - git diff with trailing comma
- const hero = {
- firstName: 'Florence',
- lastName: 'Nightingale',
- + inventorOf: ['coxcomb chart', 'modern nursing'],
- };
+// good - git diff with trailing comma
+const hero = {
+ firstName: 'Florence',
+ lastName: 'Nightingale',
++ inventorOf: ['coxcomb chart', 'modern nursing'],
+};
- // bad
- const hero = {
- firstName: 'Dana',
- lastName: 'Scully'
- };
+// bad
+const hero = {
+ firstName: 'Dana',
+ lastName: 'Scully'
+};
- const heroes = [
- 'Batman',
- 'Superman'
- ];
+const heroes = [
+ 'Batman',
+ 'Superman'
+];
- // good
- const hero = {
- firstName: 'Dana',
- lastName: 'Scully',
- };
+// good
+const hero = {
+ firstName: 'Dana',
+ lastName: 'Scully',
+};
- const heroes = [
- 'Batman',
- 'Superman',
- ];
+const heroes = [
+ 'Batman',
+ 'Superman',
+];
⬆ back to top
-Semicolons
+
Semicolons
+
+