From be137f700b13f2c23d17d3baa6938c4c9dcb9cfb Mon Sep 17 00:00:00 2001 From: Quinn Hoyer Date: Tue, 29 Apr 2014 09:07:01 -0700 Subject: [PATCH 01/19] Change to 4 Spaces --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 23f69aca96..bd8fb7dbec 100644 --- a/README.md +++ b/README.md @@ -722,12 +722,12 @@ ## Whitespace - - Use soft tabs set to 2 spaces + - Use soft tabs set to 4 spaces ```javascript // bad function() { - ∙∙∙∙var name; + ∙∙var name; } // bad @@ -737,7 +737,7 @@ // good function() { - ∙∙var name; + ∙∙∙∙var name; } ``` From df8254d73e76294a2a327ff218063c76e8ae67c6 Mon Sep 17 00:00:00 2001 From: Miguel Madero Date: Fri, 2 May 2014 15:11:01 -0700 Subject: [PATCH 02/19] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 23f69aca96..71de4ef9f9 100644 --- a/README.md +++ b/README.md @@ -1278,6 +1278,8 @@ ## Modules +** We can ignore this section since the ES6 transpiler adds 'use strict' for us, doesn't require the trailing `!` and ember forces us to use dashs for file names. + - The module should start with a `!`. This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated. [Explanation](https://github.com/airbnb/javascript/issues/44#issuecomment-13063933) - The file should be named with camelCase, live in a folder with the same name, and match the name of the single export. - Add a method called noConflict() that sets the exported module to the previous version and returns this one. From e9345deaec56a22fffa6883a672377aa1e186460 Mon Sep 17 00:00:00 2001 From: Miguel Madero Date: Fri, 2 May 2014 15:12:07 -0700 Subject: [PATCH 03/19] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 71de4ef9f9..a93ba72a4e 100644 --- a/README.md +++ b/README.md @@ -1278,7 +1278,7 @@ ## Modules -** We can ignore this section since the ES6 transpiler adds 'use strict' for us, doesn't require the trailing `!` and ember forces us to use dashs for file names. +** Note: ** We can ignore this section since the ES6 transpiler adds 'use strict' for us, doesn't require the trailing `!` and ember forces us to use dashs for file names. - The module should start with a `!`. This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated. [Explanation](https://github.com/airbnb/javascript/issues/44#issuecomment-13063933) - The file should be named with camelCase, live in a folder with the same name, and match the name of the single export. From 3103c68ece3029eb4d309013779dea55c2c6cc1e Mon Sep 17 00:00:00 2001 From: Miguel Madero Date: Tue, 6 May 2014 09:12:29 -0700 Subject: [PATCH 04/19] Update README.md Changes indentation to 4 spaces. Accepting defeat :( --- README.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a93ba72a4e..40c203793f 100644 --- a/README.md +++ b/README.md @@ -722,7 +722,7 @@ ## Whitespace - - Use soft tabs set to 2 spaces + - Use soft tabs set to 4 spaces ```javascript // bad @@ -734,10 +734,15 @@ function() { ∙var name; } + + // bad + function() { + ∙∙var name; + } // good function() { - ∙∙var name; + ∙∙∙∙var name; } ``` From 838221bf11780ca7a7193f68b5b0451df21c8b34 Mon Sep 17 00:00:00 2001 From: Miguel Madero Date: Tue, 6 May 2014 09:27:09 -0700 Subject: [PATCH 05/19] Update README.md Changes sample file-name to use dashes instead of camelCase This is needed by ember-eak, ember-cli for components and views. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 40c203793f..324be8ac75 100644 --- a/README.md +++ b/README.md @@ -1291,7 +1291,7 @@ - Always declare `'use strict';` at the top of the module. ```javascript - // fancyInput/fancyInput.js + // fancy-input/fancy-input.js !function(global) { 'use strict'; From 5cfc5e17b4813c59e118d7c234b464e12bee2c97 Mon Sep 17 00:00:00 2001 From: Miguel Madero Date: Thu, 8 May 2014 11:10:39 -0700 Subject: [PATCH 06/19] Update README.md Made it more explicit that we use dashes for filenames --- README.md | 29 +++++------------------------ 1 file changed, 5 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 324be8ac75..efad9faa7d 100644 --- a/README.md +++ b/README.md @@ -1283,37 +1283,18 @@ ## Modules -** Note: ** We can ignore this section since the ES6 transpiler adds 'use strict' for us, doesn't require the trailing `!` and ember forces us to use dashs for file names. +** Note: ** te original modules section was removed since rules didn't apply. We use the ES6 transpiler, that adds 'use strict' for us, doesn't require the trailing `!` and ember forces us to use dashes for file names. - - The module should start with a `!`. This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated. [Explanation](https://github.com/airbnb/javascript/issues/44#issuecomment-13063933) - - The file should be named with camelCase, live in a folder with the same name, and match the name of the single export. - - Add a method called noConflict() that sets the exported module to the previous version and returns this one. - - Always declare `'use strict';` at the top of the module. +**[⬆ back to top](#table-of-contents)** - ```javascript - // fancy-input/fancy-input.js +## File Names - !function(global) { - 'use strict'; +** Note: ** this section isn't part of the original AirBnB guide. - var previousFancyInput = global.FancyInput; - - function FancyInput(options) { - this.options = options || {}; - } - - FancyInput.noConflict = function noConflict() { - global.FancyInput = previousFancyInput; - return FancyInput; - }; - - global.FancyInput = FancyInput; - }(this); - ``` +- We use file-names-with-dashes because that's required for templates and components by Ember and EAK and ember-cli do that by default. **[⬆ back to top](#table-of-contents)** - ## jQuery - Prefix jQuery object variables with a `$`. From f8a5468756fa18e5a62fcb9ff9b6902494b4559d Mon Sep 17 00:00:00 2001 From: Miguel Madero Date: Thu, 8 May 2014 11:13:38 -0700 Subject: [PATCH 07/19] Update README.md --- README.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index efad9faa7d..dcb919d326 100644 --- a/README.md +++ b/README.md @@ -1283,7 +1283,33 @@ ## Modules -** Note: ** te original modules section was removed since rules didn't apply. We use the ES6 transpiler, that adds 'use strict' for us, doesn't require the trailing `!` and ember forces us to use dashes for file names. +** Note: ** We can ignore this section since the ES6 transpiler adds 'use strict' for us, doesn't require the trailing `!` and ember forces us to use dashs for file names. + + - The module should start with a `!`. This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated. [Explanation](https://github.com/airbnb/javascript/issues/44#issuecomment-13063933) + - The file should be named-with-dashes, live in a folder with the same name, and match the name of the single export. + - Add a method called noConflict() that sets the exported module to the previous version and returns this one. + - Always declare `'use strict';` at the top of the module. + + ```javascript + // fancy-input/fancy-input.js + + !function(global) { + 'use strict'; + + var previousFancyInput = global.FancyInput; + + function FancyInput(options) { + this.options = options || {}; + } + + FancyInput.noConflict = function noConflict() { + global.FancyInput = previousFancyInput; + return FancyInput; + }; + + global.FancyInput = FancyInput; + }(this); + ``` **[⬆ back to top](#table-of-contents)** From be5c2cac5384a1e6e8df6d6cb5c2ba10283a0853 Mon Sep 17 00:00:00 2001 From: Miguel Madero Date: Fri, 13 Jun 2014 11:03:27 -0700 Subject: [PATCH 08/19] Discourage the use of Em.A --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index dcb919d326..c2f0217446 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,8 @@ var items = []; ``` + *NOTE:* using an `Em.A()` or `Ember.A()` is discourage and we should favor the literal syntax array creation. See [Em.A](http://emberjs.com/api/#method_A). + - If you don't know array length use Array#push. ```javascript From 3827ed9c73eeb55d321ce8d7a51786b70db13b68 Mon Sep 17 00:00:00 2001 From: Quinn Hoyer Date: Thu, 24 Jul 2014 14:29:48 -0700 Subject: [PATCH 09/19] Discourage use of .bind() due to overwheliming performance evidence. --- README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index bd8fb7dbec..3576207d76 100644 --- a/README.md +++ b/README.md @@ -1061,7 +1061,7 @@ this._firstName = 'Panda'; ``` - - When saving a reference to `this` use `_this`. + - When saving a reference to `this` use `_this`. Never use `Function#bind(this)` if the closure is available. \[[jsperf](http://jsperf.com/bind-vs-jquery-proxy/60)\] ```javascript // bad @@ -1087,6 +1087,13 @@ console.log(_this); }; } + + // bad + function() { + return function() { + console.log(this); + }.bind(this); + } ``` - Name your functions. This is helpful for stack traces. From cc8d184865b32fa194a9cbfb5d9a6680e94f6090 Mon Sep 17 00:00:00 2001 From: Miguel Madero Date: Wed, 8 Jul 2015 10:10:46 -0700 Subject: [PATCH 10/19] Adds comment specifying the indentation of else --- README.md | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index dcb919d326..c7d089ab33 100644 --- a/README.md +++ b/README.md @@ -595,6 +595,25 @@ - For more information see [Truth Equality and JavaScript](http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) by Angus Croll + - Else blocks need to start after the closing curly brace of the if + + ```javascript + // bad + if (currentUser) { + // + } + else { + // + } + + // good + if (currentUser) { + // + } else { + // + } + ``` + **[⬆ back to top](#table-of-contents)** @@ -734,7 +753,7 @@ function() { ∙var name; } - + // bad function() { ∙∙var name; @@ -1283,7 +1302,7 @@ ## Modules -** Note: ** We can ignore this section since the ES6 transpiler adds 'use strict' for us, doesn't require the trailing `!` and ember forces us to use dashs for file names. +** Note: ** We can ignore this section since the ES6 transpiler adds 'use strict' for us, doesn't require the trailing `!` and ember forces us to use dashs for file names. - The module should start with a `!`. This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated. [Explanation](https://github.com/airbnb/javascript/issues/44#issuecomment-13063933) - The file should be named-with-dashes, live in a folder with the same name, and match the name of the single export. @@ -1315,9 +1334,9 @@ ## File Names -** Note: ** this section isn't part of the original AirBnB guide. +** Note: ** this section isn't part of the original AirBnB guide. -- We use file-names-with-dashes because that's required for templates and components by Ember and EAK and ember-cli do that by default. +- We use file-names-with-dashes because that's required for templates and components by Ember and EAK and ember-cli do that by default. **[⬆ back to top](#table-of-contents)** From fa91e62914588bc73c48916d5b9ce92ee7a54153 Mon Sep 17 00:00:00 2001 From: Miguel Madero Date: Wed, 26 Aug 2015 14:51:47 -0700 Subject: [PATCH 11/19] =?UTF-8?q?Updates=20out=20styleguide=20to=20include?= =?UTF-8?q?=20ES6=20specific=20sections=20based=20on=20Ember=E2=80=99s=20s?= =?UTF-8?q?tyleguide?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://github.com/emberjs/ember.js/blob/master/STYLEGUIDE.md --- README.md | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ca5c5fd205..9d42578fd6 100644 --- a/README.md +++ b/README.md @@ -1113,7 +1113,7 @@ console.log(_this); }; } - + // bad function() { return function() { @@ -1349,6 +1349,73 @@ **[⬆ back to top](#table-of-contents)** +## Rest Parameters + +** Note: ** this section isn't part of the original AirBnB guide. It comes from [Ember's Styleguide](https://github.com/emberjs/ember.js/blob/master/STYLEGUIDE.md) + +Since [Babel implements](https://babeljs.io/repl/#?experimental=true&playground=true&evaluate=true&loose=false&spec=false&code=function%20foo\(...args\)%20%7B%0A%20%20%0A%7D) Rest parameters in a non-leaking matter you should use them whenever applicable. + +```javascript +function foo(...args) { + args.forEach((item) => { + console.log(item); + }); +} +``` +**[⬆ back to top](#table-of-contents)** + + +## Destructuring + +** Note: ** this section isn't part of the original AirBnB guide. It comes from [Ember's Styleguide](https://github.com/emberjs/ember.js/blob/master/STYLEGUIDE.md) + +When decomposing simple arrays or objects, prefer [destructuring](http://babeljs.io/docs/learn-es6/#destructuring). + +```javascript +// array destructuring +var fullName = 'component:foo-bar'; +var [ + first, + last +] = fullName.split(':'); +``` + +```javascript +// object destructuring +var person = { + firstName: 'Stefan', + lastName: 'Penner' +}; + +var { + firstName, + lastName +} = person; +``` +**[⬆ back to top](#table-of-contents)** + + +## Comments + +** Note: ** this section isn't part of the original AirBnB guide. It comes from [Ember's Styleguide](https://github.com/emberjs/ember.js/blob/master/STYLEGUIDE.md) + ++ Use [YUIDoc](http://yui.github.io/yuidoc/syntax/index.html) comments for + documenting functions. ++ Use `//` for single line comments. + +```javascript +function foo() { + var bar = 5; + + // multiplies `bar` by 2. + fooBar(bar); + + console.log(bar); +} +``` +**[⬆ back to top](#table-of-contents)** + + ## jQuery - Prefix jQuery object variables with a `$`. From 042feb917caebfdd18412644a52c4dbd5df732f7 Mon Sep 17 00:00:00 2001 From: Claire Grimmett Date: Thu, 1 Sep 2016 20:52:12 -0700 Subject: [PATCH 12/19] Pull in updates from Airbnb and resolve conflicts --- .gitignore | 1 + .travis.yml | 17 + README.md | 2671 +++++++++++++---- linters/.eslintrc | 5 + linters/{jshintrc => .jshintrc} | 23 +- .../SublimeLinter.sublime-settings | 2 +- package.json | 35 + packages/eslint-config-airbnb-base/.babelrc | 3 + packages/eslint-config-airbnb-base/.eslintrc | 8 + .../eslint-config-airbnb-base/CHANGELOG.md | 95 + packages/eslint-config-airbnb-base/README.md | 59 + packages/eslint-config-airbnb-base/index.js | 18 + packages/eslint-config-airbnb-base/legacy.js | 21 + .../eslint-config-airbnb-base/package.json | 64 + .../rules/best-practices.js | 240 ++ .../eslint-config-airbnb-base/rules/errors.js | 113 + .../eslint-config-airbnb-base/rules/es6.js | 145 + .../rules/imports.js | 133 + .../eslint-config-airbnb-base/rules/node.js | 39 + .../eslint-config-airbnb-base/rules/strict.js | 6 + .../eslint-config-airbnb-base/rules/style.js | 312 ++ .../rules/variables.js | 41 + .../eslint-config-airbnb-base/test/.eslintrc | 12 + .../test/test-base.js | 29 + packages/eslint-config-airbnb/.babelrc | 3 + packages/eslint-config-airbnb/.eslintrc | 8 + packages/eslint-config-airbnb/CHANGELOG.md | 266 ++ packages/eslint-config-airbnb/README.md | 49 + packages/eslint-config-airbnb/base.js | 4 + packages/eslint-config-airbnb/index.js | 9 + packages/eslint-config-airbnb/legacy.js | 4 + packages/eslint-config-airbnb/package.json | 72 + .../eslint-config-airbnb/rules/react-a11y.js | 105 + packages/eslint-config-airbnb/rules/react.js | 268 ++ packages/eslint-config-airbnb/test/.eslintrc | 13 + .../eslint-config-airbnb/test/test-base.js | 33 + .../test/test-react-order.js | 93 + react/README.md | 581 ++++ 38 files changed, 4975 insertions(+), 625 deletions(-) create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 linters/.eslintrc rename linters/{jshintrc => .jshintrc} (84%) create mode 100644 package.json create mode 100644 packages/eslint-config-airbnb-base/.babelrc create mode 100644 packages/eslint-config-airbnb-base/.eslintrc create mode 100644 packages/eslint-config-airbnb-base/CHANGELOG.md create mode 100644 packages/eslint-config-airbnb-base/README.md create mode 100644 packages/eslint-config-airbnb-base/index.js create mode 100644 packages/eslint-config-airbnb-base/legacy.js create mode 100644 packages/eslint-config-airbnb-base/package.json create mode 100644 packages/eslint-config-airbnb-base/rules/best-practices.js create mode 100644 packages/eslint-config-airbnb-base/rules/errors.js create mode 100644 packages/eslint-config-airbnb-base/rules/es6.js create mode 100644 packages/eslint-config-airbnb-base/rules/imports.js create mode 100644 packages/eslint-config-airbnb-base/rules/node.js create mode 100644 packages/eslint-config-airbnb-base/rules/strict.js create mode 100644 packages/eslint-config-airbnb-base/rules/style.js create mode 100644 packages/eslint-config-airbnb-base/rules/variables.js create mode 100644 packages/eslint-config-airbnb-base/test/.eslintrc create mode 100644 packages/eslint-config-airbnb-base/test/test-base.js create mode 100644 packages/eslint-config-airbnb/.babelrc create mode 100644 packages/eslint-config-airbnb/.eslintrc create mode 100644 packages/eslint-config-airbnb/CHANGELOG.md create mode 100644 packages/eslint-config-airbnb/README.md create mode 100644 packages/eslint-config-airbnb/base.js create mode 100644 packages/eslint-config-airbnb/index.js create mode 100644 packages/eslint-config-airbnb/legacy.js create mode 100644 packages/eslint-config-airbnb/package.json create mode 100644 packages/eslint-config-airbnb/rules/react-a11y.js create mode 100644 packages/eslint-config-airbnb/rules/react.js create mode 100644 packages/eslint-config-airbnb/test/.eslintrc create mode 100644 packages/eslint-config-airbnb/test/test-base.js create mode 100644 packages/eslint-config-airbnb/test/test-react-order.js create mode 100644 react/README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..3c3629e647 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000..773761966a --- /dev/null +++ b/.travis.yml @@ -0,0 +1,17 @@ +language: node_js +node_js: + - "6" + - "5" + - "4" +env: + - 'TEST_DIR=packages/eslint-config-airbnb' + - 'TEST_DIR=packages/eslint-config-airbnb-base' +before_install: + - 'cd $TEST_DIR' + - 'if [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi' + - 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then npm install -g npm; fi' +script: + - 'npm run travis' +sudo: false +matrix: + fast_finish: true diff --git a/README.md b/README.md index 9d42578fd6..cafaaccb6a 100644 --- a/README.md +++ b/README.md @@ -2,18 +2,23 @@ *A mostly reasonable approach to JavaScript* - -## Table of Contents +# Table of Contents 1. [Types](#types) + 1. [References](#references) 1. [Objects](#objects) 1. [Arrays](#arrays) + 1. [Destructuring](#destructuring) 1. [Strings](#strings) 1. [Functions](#functions) + 1. [Arrow Functions](#arrow-functions) + 1. [Classes & Constructors](#classes--constructors) + 1. [Modules](#modules) + 1. [Iterators and Generators](#iterators-and-generators) 1. [Properties](#properties) 1. [Variables](#variables) 1. [Hoisting](#hoisting) - 1. [Conditional Expressions & Equality](#conditional-expressions--equality) + 1. [Comparison Operators & Equality](#comparison-operators--equality) 1. [Blocks](#blocks) 1. [Comments](#comments) 1. [Whitespace](#whitespace) @@ -22,11 +27,10 @@ 1. [Type Casting & Coercion](#type-casting--coercion) 1. [Naming Conventions](#naming-conventions) 1. [Accessors](#accessors) - 1. [Constructors](#constructors) 1. [Events](#events) - 1. [Modules](#modules) 1. [jQuery](#jquery) 1. [ECMAScript 5 Compatibility](#ecmascript-5-compatibility) + 1. [ECMAScript 6+ (ES 2015+) Styles](#ecmascript-6-styles) 1. [Testing](#testing) 1. [Performance](#performance) 1. [Resources](#resources) @@ -38,7 +42,8 @@ ## Types - - **Primitives**: When you access a primitive type you work directly on its value + + - [1.1](#types--primitives) **Primitives**: When you access a primitive type you work directly on its value. + `string` + `number` @@ -47,22 +52,24 @@ + `undefined` ```javascript - var foo = 1, - bar = foo; + const foo = 1; + let bar = foo; bar = 9; console.log(foo, bar); // => 1, 9 ``` - - **Complex**: When you access a complex type you work on a reference to its value + + + - [1.2](#types--complex) **Complex**: When you access a complex type you work on a reference to its value. + `object` + `array` + `function` ```javascript - var foo = [1, 2], - bar = foo; + const foo = [1, 2]; + const bar = foo; bar[0] = 9; @@ -71,74 +78,232 @@ **[⬆ back to top](#table-of-contents)** +## References + + + - [2.1](#references--prefer-const) Use `const` for all of your references; avoid using `var`. eslint: [`prefer-const`](http://eslint.org/docs/rules/prefer-const.html), [`no-const-assign`](http://eslint.org/docs/rules/no-const-assign.html) + + > Why? This ensures that you can't reassign your references, which can lead to bugs and difficult to comprehend code. + + ```javascript + // bad + var a = 1; + var b = 2; + + // good + const a = 1; + const b = 2; + ``` + + + - [2.2](#references--disallow-var) If you must reassign references, use `let` instead of `var`. eslint: [`no-var`](http://eslint.org/docs/rules/no-var.html) jscs: [`disallowVar`](http://jscs.info/rule/disallowVar) + + > Why? `let` is block-scoped rather than function-scoped like `var`. + + ```javascript + // bad + var count = 1; + if (true) { + count += 1; + } + + // good, use the let. + let count = 1; + if (true) { + count += 1; + } + ``` + + + - [2.3](#references--block-scope) Note that both `let` and `const` are block-scoped. + + ```javascript + // const and let only exist in the blocks they are defined in. + { + let a = 1; + const b = 1; + } + console.log(a); // ReferenceError + console.log(b); // ReferenceError + ``` + +**[⬆ back to top](#table-of-contents)** + ## Objects - - Use the literal syntax for object creation. + + - [3.1](#objects--no-new) Use the literal syntax for object creation. eslint: [`no-new-object`](http://eslint.org/docs/rules/no-new-object.html) + + ```javascript + // bad + const item = new Object(); + + // good + const item = {}; + ``` + + + - [3.4](#es6-computed-properties) Use computed property names when creating objects with dynamic property names. + + > Why? They allow you to define all the properties of an object in one place. ```javascript + + function getKey(k) { + return `a key named ${k}`; + } + // bad - var item = new Object(); + const obj = { + id: 5, + name: 'San Francisco', + }; + obj[getKey('enabled')] = true; // good - var item = {}; + const obj = { + id: 5, + name: 'San Francisco', + [getKey('enabled')]: true, + }; ``` - - Don't use [reserved words](http://es5.github.io/#x7.6.1) as keys. It won't work in IE8. [More info](https://github.com/airbnb/javascript/issues/61) + + - [3.5](#es6-object-shorthand) Use object method shorthand. eslint: [`object-shorthand`](http://eslint.org/docs/rules/object-shorthand.html) jscs: [`requireEnhancedObjectLiterals`](http://jscs.info/rule/requireEnhancedObjectLiterals) ```javascript // bad - var superman = { - default: { clark: 'kent' }, - private: true + const atom = { + value: 1, + + addValue: function (value) { + return atom.value + value; + }, }; // good - var superman = { - defaults: { clark: 'kent' }, - hidden: true + const atom = { + value: 1, + + addValue(value) { + return atom.value + value; + }, }; ``` - - Use readable synonyms in place of reserved words. + + - [3.6](#es6-object-concise) Use property value shorthand. eslint: [`object-shorthand`](http://eslint.org/docs/rules/object-shorthand.html) jscs: [`requireEnhancedObjectLiterals`](http://jscs.info/rule/requireEnhancedObjectLiterals) + + > Why? It is shorter to write and descriptive. ```javascript + const lukeSkywalker = 'Luke Skywalker'; + // bad - var superman = { - class: 'alien' + const obj = { + lukeSkywalker: lukeSkywalker, }; + // good + const obj = { + lukeSkywalker, + }; + ``` + + + - [3.7](#objects--grouped-shorthand) Group your shorthand properties at the beginning of your object declaration. + + > Why? It's easier to tell which properties are using the shorthand. + + ```javascript + const anakinSkywalker = 'Anakin Skywalker'; + const lukeSkywalker = 'Luke Skywalker'; + // bad - var superman = { - klass: 'alien' + const obj = { + episodeOne: 1, + twoJediWalkIntoACantina: 2, + lukeSkywalker, + episodeThree: 3, + mayTheFourth: 4, + anakinSkywalker, }; // good - var superman = { - type: 'alien' + const obj = { + lukeSkywalker, + anakinSkywalker, + episodeOne: 1, + twoJediWalkIntoACantina: 2, + episodeThree: 3, + mayTheFourth: 4, }; ``` + + - [3.8](#objects--quoted-props) Only quote properties that are invalid identifiers. eslint: [`quote-props`](http://eslint.org/docs/rules/quote-props.html) jscs: [`disallowQuotedKeysInObjects`](http://jscs.info/rule/disallowQuotedKeysInObjects) + + > Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines. + + ```javascript + // bad + const bad = { + 'foo': 3, + 'bar': 4, + 'data-blah': 5, + }; + + // good + const good = { + foo: 3, + bar: 4, + 'data-blah': 5, + }; + ``` + + + - [3.9](#objects--prototype-builtins) Do not call `Object.prototype` methods directly, such as `hasOwnProperty`, `propertyIsEnumerable`, and `isPrototypeOf`. + + > Why? These methods may be shadowed by properties on the object in question - consider `{ hasOwnProperty: false }` - or, the object may be a null object (`Object.create(null)`). + + ```javascript + // bad + console.log(object.hasOwnProperty(key)); + + // good + console.log(Object.prototype.hasOwnProperty.call(object, key)); + + // best + const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope. + /* or */ + const has = require('has'); + … + console.log(has.call(object, key)); + ``` + **[⬆ back to top](#table-of-contents)** ## Arrays - - Use the literal syntax for array creation + + - [4.1](#arrays--literals) Use the literal syntax for array creation. eslint: [`no-array-constructor`](http://eslint.org/docs/rules/no-array-constructor.html) ```javascript // bad - var items = new Array(); + const items = new Array(); // good - var items = []; + const items = []; ``` *NOTE:* using an `Em.A()` or `Ember.A()` is discourage and we should favor the literal syntax array creation. See [Em.A](http://emberjs.com/api/#method_A). - - If you don't know array length use Array#push. - ```javascript - var someStack = []; + + - [4.2](#arrays--push) Use [Array#push](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push) instead of direct assignment to add items to an array. + ```javascript + const someStack = []; // bad someStack[someStack.length] = 'abracadabra'; @@ -147,113 +312,231 @@ someStack.push('abracadabra'); ``` - - When you need to copy an array use Array#slice. [jsPerf](http://jsperf.com/converting-arguments-to-an-array/7) + + - [4.3](#es6-array-spreads) Use array spreads `...` to copy arrays. ```javascript - var len = items.length, - itemsCopy = [], - i; - // bad + const len = items.length; + const itemsCopy = []; + let i; + for (i = 0; i < len; i++) { itemsCopy[i] = items[i]; } // good - itemsCopy = items.slice(); + const itemsCopy = [...items]; ``` - - To convert an array-like object to an array, use Array#slice. + + - [4.4](#arrays--from) To convert an array-like object to an array, use [Array.from](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from). ```javascript - function trigger() { - var args = Array.prototype.slice.call(arguments); - ... - } + const foo = document.querySelectorAll('.foo'); + const nodes = Array.from(foo); + ``` + + + - [4.5](#arrays--callback-return) Use return statements in array method callbacks. It's ok to omit the return if the function body consists of a single statement following [8.2](#8.2). eslint: [`array-callback-return`](http://eslint.org/docs/rules/array-callback-return) + + ```javascript + // good + [1, 2, 3].map((x) => { + const y = x + 1; + return x * y; + }); + + // good + [1, 2, 3].map(x => x + 1); + + // bad + const flat = {}; + [[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => { + const flatten = memo.concat(item); + flat[index] = flatten; + }); + + // good + const flat = {}; + [[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => { + const flatten = memo.concat(item); + flat[index] = flatten; + return flatten; + }); + + // bad + inbox.filter((msg) => { + const { subject, author } = msg; + if (subject === 'Mockingbird') { + return author === 'Harper Lee'; + } else { + return false; + } + }); + + // good + inbox.filter((msg) => { + const { subject, author } = msg; + if (subject === 'Mockingbird') { + return author === 'Harper Lee'; + } + + return false; + }); ``` **[⬆ back to top](#table-of-contents)** +## Destructuring + + + - [5.1](#destructuring--object) Use object destructuring when accessing and using multiple properties of an object. jscs: [`requireObjectDestructuring`](http://jscs.info/rule/requireObjectDestructuring) -## Strings + > Why? Destructuring saves you from creating temporary references for those properties. + + ```javascript + // bad + function getFullName(user) { + const firstName = user.firstName; + const lastName = user.lastName; + + return `${firstName} ${lastName}`; + } + + // good + function getFullName(user) { + const { firstName, lastName } = user; + return `${firstName} ${lastName}`; + } - - Use single quotes `''` for strings + // best + function getFullName({ firstName, lastName }) { + return `${firstName} ${lastName}`; + } + ``` + + + - [5.2](#destructuring--array) Use array destructuring. jscs: [`requireArrayDestructuring`](http://jscs.info/rule/requireArrayDestructuring) ```javascript + const arr = [1, 2, 3, 4]; + // bad - var name = "Bob Parr"; + const first = arr[0]; + const second = arr[1]; // good - var name = 'Bob Parr'; + const [first, second] = arr; + ``` + + + - [5.3](#destructuring--object-over-array) Use object destructuring for multiple return values, not array destructuring. jscs: [`disallowArrayDestructuringReturn`](http://jscs.info/rule/disallowArrayDestructuringReturn) + > Why? You can add new properties over time or change the order of things without breaking call sites. + + ```javascript // bad - var fullName = "Bob " + this.lastName; + function processInput(input) { + // then a miracle occurs + return [left, right, top, bottom]; + } + + // the caller needs to think about the order of return data + const [left, __, top] = processInput(input); // good - var fullName = 'Bob ' + this.lastName; + function processInput(input) { + // then a miracle occurs + return { left, right, top, bottom }; + } + + // the caller selects only the data they need + const { left, top } = processInput(input); ``` - - Strings longer than 80 characters should be written across multiple lines using string concatenation. - - Note: If overused, long strings with concatenation could impact performance. [jsPerf](http://jsperf.com/ya-string-concat) & [Discussion](https://github.com/airbnb/javascript/issues/40) + +**[⬆ back to top](#table-of-contents)** + +## Strings + + + - [6.1](#strings--quotes) Use single quotes `''` for strings. eslint: [`quotes`](http://eslint.org/docs/rules/quotes.html) jscs: [`validateQuoteMarks`](http://jscs.info/rule/validateQuoteMarks) ```javascript // bad - var errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.'; + const name = "Capt. Janeway"; + + // bad - template literals should contain interpolation or newlines + const name = `Capt. Janeway`; + + // good + const name = 'Capt. Janeway'; + ``` + + + - [6.2](#strings--line-length) Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation. + > Why? Broken strings are painful to work with and make code less searchable. + + ```javascript // bad - var errorMessage = 'This is a super long error that was thrown because \ + const errorMessage = 'This is a super long error that was thrown because \ of Batman. When you stop to think about how Batman had anything to do \ with this, you would get nowhere \ fast.'; - // good - var errorMessage = 'This is a super long error that was thrown because ' + + // bad + const errorMessage = 'This is a super long error that was thrown because ' + 'of Batman. When you stop to think about how Batman had anything to do ' + 'with this, you would get nowhere fast.'; - ``` - - - When programmatically building up a string, use Array#join instead of string concatenation. Mostly for IE: [jsPerf](http://jsperf.com/string-vs-array-concat/2). - ```javascript - var items, - messages, - length, - i; + // good + const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.'; + ``` - messages = [{ - state: 'success', - message: 'This one worked.' - }, { - state: 'success', - message: 'This one worked as well.' - }, { - state: 'error', - message: 'This one did not work.' - }]; + + - [6.4](#es6-template-literals) When programmatically building up strings, use template strings instead of concatenation. eslint: [`prefer-template`](http://eslint.org/docs/rules/prefer-template.html) [`template-curly-spacing`](http://eslint.org/docs/rules/template-curly-spacing) jscs: [`requireTemplateStrings`](http://jscs.info/rule/requireTemplateStrings) - length = messages.length; + > Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features. + ```javascript // bad - function inbox(messages) { - items = '
    '; + function sayHi(name) { + return 'How are you, ' + name + '?'; + } - for (i = 0; i < length; i++) { - items += '
  • ' + messages[i].message + '
  • '; - } + // bad + function sayHi(name) { + return ['How are you, ', name, '?'].join(); + } - return items + '
'; + // bad + function sayHi(name) { + return `How are you, ${ name }?`; } // good - function inbox(messages) { - items = []; + function sayHi(name) { + return `How are you, ${name}?`; + } + ``` - for (i = 0; i < length; i++) { - items[i] = messages[i].message; - } + + - [6.5](#strings--eval) Never use `eval()` on a string, it opens too many vulnerabilities. - return '
  • ' + items.join('
  • ') + '
'; - } + + - [6.6](#strings--escaping) Do not unnecessarily escape characters in strings. eslint: [`no-useless-escape`](http://eslint.org/docs/rules/no-useless-escape) + + > Why? Backslashes harm readability, thus they should only be present when necessary. + + ```javascript + // bad + const foo = '\'this\' \i\s \"quoted\"'; + + // good + const foo = '\'this\' is "quoted"'; + const foo = `'this' is "quoted"`; ``` **[⬆ back to top](#table-of-contents)** @@ -261,27 +544,38 @@ ## Functions - - Function expressions: + + - [7.1](#functions--declarations) Use function declarations instead of function expressions. eslint: [`func-style`](http://eslint.org/docs/rules/func-style) jscs: [`requireFunctionDeclarations`](http://jscs.info/rule/requireFunctionDeclarations) + + > Why? Function declarations are named, so they're easier to identify in call stacks. Also, the whole body of a function declaration is hoisted, whereas only the reference of a function expression is hoisted. This rule makes it possible to always use [Arrow Functions](#arrow-functions) in place of function expressions. ([discussion](https://github.com/airbnb/javascript/issues/794)) ```javascript - // anonymous function expression - var anonymous = function() { - return true; + // bad + const foo = function () { }; - // named function expression - var named = function named() { - return true; - }; + // good + function foo() { + } + ``` + + + - [7.2](#functions--iife) Wrap immediately invoked function expressions in parentheses. eslint: [`wrap-iife`](http://eslint.org/docs/rules/wrap-iife.html) jscs: [`requireParenthesesAroundIIFE`](http://jscs.info/rule/requireParenthesesAroundIIFE) + > Why? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this. Note that in a world with modules everywhere, you almost never need an IIFE. + + ```javascript // immediately-invoked function expression (IIFE) - (function() { + (function () { console.log('Welcome to the Internet. Please follow me.'); - })(); + }()); ``` - - 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. - - **Note:** ECMA-262 defines a `block` as a list of statements. A function declaration is not a statement. [Read ECMA-262's note on this issue](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf#page=97). + + - [7.3](#functions--in-blocks) 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. eslint: [`no-loop-func`](http://eslint.org/docs/rules/no-loop-func.html) + + + - [7.4](#functions--note-on-blocks) **Note:** ECMA-262 defines a `block` as a list of statements. A function declaration is not a statement. [Read ECMA-262's note on this issue](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf#page=97). ```javascript // bad @@ -291,63 +585,725 @@ } } - // good - var test; - if (currentUser) { - test = function test() { - console.log('Yup.'); - }; + // good + let test; + if (currentUser) { + test = () => { + console.log('Yup.'); + }; + } + ``` + + + - [7.5](#functions--arguments-shadow) Never name a parameter `arguments`. This will take precedence over the `arguments` object that is given to every function scope. + + ```javascript + // bad + function nope(name, options, arguments) { + // ...stuff... + } + + // good + function yup(name, options, args) { + // ...stuff... + } + ``` + + + - [7.6](#es6-rest) Never use `arguments`, opt to use rest syntax `...` instead. eslint: [`prefer-rest-params`](http://eslint.org/docs/rules/prefer-rest-params) + + > Why? `...` is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like like `arguments`. + + ```javascript + // bad + function concatenateAll() { + const args = Array.prototype.slice.call(arguments); + return args.join(''); + } + + // good + function concatenateAll(...args) { + return args.join(''); + } + ``` + + + - [7.7](#es6-default-parameters) Use default parameter syntax rather than mutating function arguments. + + ```javascript + // really bad + function handleThings(opts) { + // No! We shouldn't mutate function arguments. + // Double bad: if opts is falsy it'll be set to an object which may + // be what you want but it can introduce subtle bugs. + opts = opts || {}; + // ... + } + + // still bad + function handleThings(opts) { + if (opts === void 0) { + opts = {}; + } + // ... + } + + // good + function handleThings(opts = {}) { + // ... + } + ``` + + + - [7.8](#functions--default-side-effects) Avoid side effects with default parameters. + + > Why? They are confusing to reason about. + + ```javascript + var b = 1; + // bad + function count(a = b++) { + console.log(a); + } + count(); // 1 + count(); // 2 + count(3); // 3 + count(); // 3 + ``` + + + - [7.9](#functions--defaults-last) Always put default parameters last. + + ```javascript + // bad + function handleThings(opts = {}, name) { + // ... + } + + // good + function handleThings(name, opts = {}) { + // ... + } + ``` + + + - [7.10](#functions--constructor) Never use the Function constructor to create a new function. eslint: [`no-new-func`](http://eslint.org/docs/rules/no-new-func) + + > Why? Creating a function in this way evaluates a string similarly to eval(), which opens vulnerabilities. + + ```javascript + // bad + var add = new Function('a', 'b', 'return a + b'); + + // still bad + var subtract = Function('a', 'b', 'return a - b'); + ``` + + + - [7.11](#functions--signature-spacing) Spacing in a function signature. eslint: [`space-before-function-paren`](http://eslint.org/docs/rules/space-before-function-paren) [`space-before-blocks`](http://eslint.org/docs/rules/space-before-blocks) + + > Why? Consistency is good, and you shouldn’t have to add or remove a space when adding or removing a name. + + ```javascript + // bad + const f = function(){}; + const g = function (){}; + const h = function() {}; + + // good + const x = function () {}; + const y = function a() {}; + ``` + + + - [7.12](#functions--mutate-params) Never mutate parameters. eslint: [`no-param-reassign`](http://eslint.org/docs/rules/no-param-reassign.html) + + > Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller. + + ```javascript + // bad + function f1(obj) { + obj.key = 1; + }; + + // good + function f2(obj) { + const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1; + }; + ``` + + + - [7.13](#functions--reassign-params) Never reassign parameters. eslint: [`no-param-reassign`](http://eslint.org/docs/rules/no-param-reassign.html) + + > Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the `arguments` object. It can also cause optimization issues, especially in V8. + + ```javascript + // bad + function f1(a) { + a = 1; + } + + function f2(a) { + if (!a) { a = 1; } + } + + // good + function f3(a) { + const b = a || 1; + } + + function f4(a = 1) { + } + ``` + + + - [7.14](#functions--spread-vs-apply) Prefer the use of the spread operator `...` to call variadic functions. eslint: [`prefer-spread`](http://eslint.org/docs/rules/prefer-spread) + + > Why? It's cleaner, you don't need to supply a context, and you can not easily compose `new` with `apply`. + + ```javascript + // bad + const x = [1, 2, 3, 4, 5]; + console.log.apply(console, x); + + // good + const x = [1, 2, 3, 4, 5]; + console.log(...x); + + // bad + new (Function.prototype.bind.apply(Date, [null, 2016, 08, 05])); + + // good + new Date(...[2016, 08, 05]); + ``` + +**[⬆ back to top](#table-of-contents)** + +## Arrow Functions + + + - [8.1](#arrows--use-them) When you must use function expressions (as when passing an anonymous function), use arrow function notation. eslint: [`prefer-arrow-callback`](http://eslint.org/docs/rules/prefer-arrow-callback.html), [`arrow-spacing`](http://eslint.org/docs/rules/arrow-spacing.html) jscs: [`requireArrowFunctions`](http://jscs.info/rule/requireArrowFunctions) + + > Why? It creates a version of the function that executes in the context of `this`, which is usually what you want, and is a more concise syntax. + + > Why not? If you have a fairly complicated function, you might move that logic out into its own function declaration. + + ```javascript + // bad + [1, 2, 3].map(function (x) { + const y = x + 1; + return x * y; + }); + + // good + [1, 2, 3].map((x) => { + const y = x + 1; + return x * y; + }); + ``` + + + - [8.2](#arrows--implicit-return) If the function body consists of a single expression, omit the braces and use the implicit return. Otherwise, keep the braces and use a `return` statement. eslint: [`arrow-parens`](http://eslint.org/docs/rules/arrow-parens.html), [`arrow-body-style`](http://eslint.org/docs/rules/arrow-body-style.html) jscs: [`disallowParenthesesAroundArrowParam`](http://jscs.info/rule/disallowParenthesesAroundArrowParam), [`requireShorthandArrowFunctions`](http://jscs.info/rule/requireShorthandArrowFunctions) + + > Why? Syntactic sugar. It reads well when multiple functions are chained together. + + ```javascript + // bad + [1, 2, 3].map(number => { + const nextNumber = number + 1; + `A string containing the ${nextNumber}.`; + }); + + // good + [1, 2, 3].map(number => `A string containing the ${number}.`); + + // good + [1, 2, 3].map((number) => { + const nextNumber = number + 1; + return `A string containing the ${nextNumber}.`; + }); + + // good + [1, 2, 3].map((number, index) => ({ + index: number + })); + ``` + + + - [8.3](#arrows--paren-wrap) In case the expression spans over multiple lines, wrap it in parentheses for better readability. + + > Why? It shows clearly where the function starts and ends. + + ```js + // bad + [1, 2, 3].map(number => 'As time went by, the string containing the ' + + `${number} became much longer. So we needed to break it over multiple ` + + 'lines.' + ); + + // good + [1, 2, 3].map(number => ( + `As time went by, the string containing the ${number} became much ` + + 'longer. So we needed to break it over multiple lines.' + )); + ``` + + + - [8.4](#arrows--one-arg-parens) If your function takes a single argument and doesn’t use braces, omit the parentheses. Otherwise, always include parentheses around arguments. eslint: [`arrow-parens`](http://eslint.org/docs/rules/arrow-parens.html) jscs: [`disallowParenthesesAroundArrowParam`](http://jscs.info/rule/disallowParenthesesAroundArrowParam) + + > Why? Less visual clutter. + + ```js + // bad + [1, 2, 3].map((x) => x * x); + + // good + [1, 2, 3].map(x => x * x); + + // good + [1, 2, 3].map(number => ( + `A long string with the ${number}. It’s so long that we’ve broken it ` + + 'over multiple lines!' + )); + + // bad + [1, 2, 3].map(x => { + const y = x + 1; + return x * y; + }); + + // good + [1, 2, 3].map((x) => { + const y = x + 1; + return x * y; + }); + ``` + + + - [8.5](#arrows--confusing) Avoid confusing arrow function syntax (`=>`) with comparison operators (`<=`, `>=`). eslint: [`no-confusing-arrow`](http://eslint.org/docs/rules/no-confusing-arrow) + + ```js + // bad + const itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize; + + // bad + const itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize; + + // good + const itemHeight = item => (item.height > 256 ? item.largeSize : item.smallSize); + + // good + const itemHeight = (item) => { + const { height, largeSize, smallSize } = item; + return height > 256 ? largeSize : smallSize; + }; + ``` + +**[⬆ back to top](#table-of-contents)** + + +## Classes & Constructors + + + - [9.1](#constructors--use-class) Always use `class`. Avoid manipulating `prototype` directly. + + > Why? `class` syntax is more concise and easier to reason about. + + ```javascript + // bad + function Queue(contents = []) { + this.queue = [...contents]; + } + Queue.prototype.pop = function () { + const value = this.queue[0]; + this.queue.splice(0, 1); + return value; + }; + + + // good + class Queue { + constructor(contents = []) { + this.queue = [...contents]; + } + pop() { + const value = this.queue[0]; + this.queue.splice(0, 1); + return value; + } + } + ``` + + + - [9.2](#constructors--extends) Use `extends` for inheritance. + + > Why? It is a built-in way to inherit prototype functionality without breaking `instanceof`. + + ```javascript + // bad + const inherits = require('inherits'); + function PeekableQueue(contents) { + Queue.apply(this, contents); + } + inherits(PeekableQueue, Queue); + PeekableQueue.prototype.peek = function () { + return this._queue[0]; + } + + // good + class PeekableQueue extends Queue { + peek() { + return this._queue[0]; + } + } + ``` + + + - [9.3](#constructors--chaining) Methods can return `this` to help with method chaining. + + ```javascript + // bad + Jedi.prototype.jump = function () { + this.jumping = true; + return true; + }; + + Jedi.prototype.setHeight = function (height) { + this.height = height; + }; + + const luke = new Jedi(); + luke.jump(); // => true + luke.setHeight(20); // => undefined + + // good + class Jedi { + jump() { + this.jumping = true; + return this; + } + + setHeight(height) { + this.height = height; + return this; + } + } + + const luke = new Jedi(); + + luke.jump() + .setHeight(20); + ``` + + + + - [9.4](#constructors--tostring) It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects. + + ```javascript + class Jedi { + constructor(options = {}) { + this.name = options.name || 'no name'; + } + + getName() { + return this.name; + } + + toString() { + return `Jedi - ${this.getName()}`; + } + } + ``` + + + - [9.5](#constructors--no-useless) Classes have a default constructor if one is not specified. An empty constructor function or one that just delegates to a parent class is unnecessary. eslint: [`no-useless-constructor`](http://eslint.org/docs/rules/no-useless-constructor) + + ```javascript + // bad + class Jedi { + constructor() {} + + getName() { + return this.name; + } + } + + // bad + class Rey extends Jedi { + constructor(...args) { + super(...args); + } + } + + // good + class Rey extends Jedi { + constructor(...args) { + super(...args); + this.name = 'Rey'; + } + } + ``` + + + - [9.6](#classes--no-duplicate-members) Avoid duplicate class members. eslint: [`no-dupe-class-members`](http://eslint.org/docs/rules/no-dupe-class-members) + + > Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug. + + ```javascript + // bad + class Foo { + bar() { return 1; } + bar() { return 2; } + } + + // good + class Foo { + bar() { return 1; } + } + + // good + class Foo { + bar() { return 2; } + } + ``` + + +**[⬆ back to top](#table-of-contents)** + + +## Modules + + + - [10.1](#modules--use-them) Always use modules (`import`/`export`) over a non-standard module system. You can always transpile to your preferred module system. + + > Why? Modules are the future, let's start using the future now. + + ```javascript + // bad + const AirbnbStyleGuide = require('./AirbnbStyleGuide'); + module.exports = AirbnbStyleGuide.es6; + + // ok + import AirbnbStyleGuide from './AirbnbStyleGuide'; + export default AirbnbStyleGuide.es6; + + // best + import { es6 } from './AirbnbStyleGuide'; + export default es6; + ``` + + + - [10.2](#modules--no-wildcard) Do not use wildcard imports. + + > Why? This makes sure you have a single default export. + + ```javascript + // bad + import * as AirbnbStyleGuide from './AirbnbStyleGuide'; + + // good + import AirbnbStyleGuide from './AirbnbStyleGuide'; + ``` + + + - [10.3](#modules--no-export-from-import) And do not export directly from an import. + + > Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent. + + ```javascript + // bad + // filename es6.js + export { es6 as default } from './airbnbStyleGuide'; + + // good + // filename es6.js + import { es6 } from './AirbnbStyleGuide'; + export default es6; + ``` + + + - [10.4](#modules--no-duplicate-imports) Only import from a path in one place. + eslint: [`no-duplicate-imports`](http://eslint.org/docs/rules/no-duplicate-imports) + > Why? Having multiple lines that import from the same path can make code harder to maintain. + + ```javascript + // bad + import foo from 'foo'; + // … some other imports … // + import { named1, named2 } from 'foo'; + + // good + import foo, { named1, named2 } from 'foo'; + + // good + import foo, { + named1, + named2, + } from 'foo'; + ``` + + + - [10.5](#modules--no-mutable-exports) Do not export mutable bindings. + eslint: [`import/no-mutable-exports`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md) + > Why? Mutation should be avoided in general, but in particular when exporting mutable bindings. While this technique may be needed for some special cases, in general, only constant references should be exported. + + ```javascript + // bad + let foo = 3; + export { foo } + + // good + const foo = 3; + export { foo } + ``` + + + - [10.6](#modules--prefer-default-export) In modules with a single export, prefer default export over named export. + eslint: [`import/prefer-default-export`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md) + + ```javascript + // bad + export function foo() {} + + // good + export default function foo() {} + ``` + + + - [10.7](#modules--imports-first) Put all `import`s above non-import statements. + eslint: [`import/imports-first`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/imports-first.md) + > Why? Since `import`s are hoisted, keeping them all at the top prevents surprising behavior. + + ```javascript + // bad + import foo from 'foo'; + foo.init(); + + import bar from 'bar'; + + // good + import foo from 'foo'; + import bar from 'bar'; + + foo.init(); + ``` + +**[⬆ back to top](#table-of-contents)** + +## Iterators and Generators + + + - [11.1](#iterators--nope) Don't use iterators. Prefer JavaScript's higher-order functions instead of loops like `for-in` or `for-of`. eslint: [`no-iterator`](http://eslint.org/docs/rules/no-iterator.html) [`no-restricted-syntax`](http://eslint.org/docs/rules/no-restricted-syntax) + + > Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects. + + > Use `map()` / `every()` / `filter()` / `find()` / `findIndex()` / `reduce()` / `some()` / ... to iterate over arrays, and `Object.keys()` / `Object.values()` / `Object.entries()` to produce arrays so you can iterate over objects. + + ```javascript + const numbers = [1, 2, 3, 4, 5]; + + // bad + let sum = 0; + for (let num of numbers) { + sum += num; + } + + sum === 15; + + // good + let sum = 0; + numbers.forEach(num => sum += num); + sum === 15; + + // best (use the functional force) + const sum = numbers.reduce((total, num) => total + num, 0); + sum === 15; + ``` + + + - [11.2](#generators--nope) Don't use generators for now. + + > Why? They don't transpile well to ES5. + + + - [11.3](#generators--spacing) If you must use generators, or if you disregard [our advice](#generators--nope), make sure their function signature is spaced properly. eslint: [`generator-star-spacing`](http://eslint.org/docs/rules/generator-star-spacing) + + > Why? `function` and `*` are part of the same conceptual keyword - `*` is not a modifier for `function`, `function*` is a unique construct, different from `function`. + + ```js + // bad + function * foo() { + } + + const bar = function * () { + } + + const baz = function *() { + } + + const quux = function*() { + } + + function*foo() { + } + + function *foo() { } - ``` - - Never name a parameter `arguments`, this will take precedence over the `arguments` object that is given to every function scope. + // very bad + function + * + foo() { + } - ```javascript - // bad - function nope(name, options, arguments) { - // ...stuff... + const wat = function + * + () { } // good - function yup(name, options, args) { - // ...stuff... + function* foo() { + } + + const foo = function* () { } ``` **[⬆ back to top](#table-of-contents)** - ## Properties - - Use dot notation when accessing properties. + + - [12.1](#properties--dot) Use dot notation when accessing properties. eslint: [`dot-notation`](http://eslint.org/docs/rules/dot-notation.html) jscs: [`requireDotNotation`](http://jscs.info/rule/requireDotNotation) ```javascript - var luke = { + const luke = { jedi: true, - age: 28 + age: 28, }; // bad - var isJedi = luke['jedi']; + const isJedi = luke['jedi']; // good - var isJedi = luke.jedi; + const isJedi = luke.jedi; ``` - - Use subscript notation `[]` when accessing properties with a variable. + + - [12.2](#properties--bracket) Use bracket notation `[]` when accessing properties with a variable. ```javascript - var luke = { + const luke = { jedi: true, - age: 28 + age: 28, }; function getProp(prop) { return luke[prop]; } - var isJedi = getProp('jedi'); + const isJedi = getProp('jedi'); ``` **[⬆ back to top](#table-of-contents)** @@ -355,65 +1311,82 @@ ## Variables - - Always use `var` to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that. + + - [13.1](#variables--const) Always use `const` to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that. eslint: [`no-undef`](http://eslint.org/docs/rules/no-undef) [`prefer-const`](http://eslint.org/docs/rules/prefer-const) ```javascript // bad superPower = new SuperPower(); // good - var superPower = new SuperPower(); + const superPower = new SuperPower(); ``` - - Use one `var` declaration for multiple variables and declare each variable on a newline. + + - [13.2](#variables--one-const) Use one `const` declaration per variable. eslint: [`one-var`](http://eslint.org/docs/rules/one-var.html) jscs: [`disallowMultipleVarDecl`](http://jscs.info/rule/disallowMultipleVarDecl) + + > Why? It's easier to add new variable declarations this way, and you never have to worry about swapping out a `;` for a `,` or introducing punctuation-only diffs. You can also step through each declaration with the debugger, instead of jumping through all of them at once. ```javascript // bad - var items = getItems(); - var goSportsTeam = true; - var dragonball = 'z'; - - // good - var items = getItems(), + const items = getItems(), goSportsTeam = true, dragonball = 'z'; + + // bad + // (compare to above, and try to spot the mistake) + const items = getItems(), + goSportsTeam = true; + dragonball = 'z'; + + // good + const items = getItems(); + const goSportsTeam = true; + const dragonball = 'z'; ``` - - Declare unassigned variables last. This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables. + + - [13.3](#variables--const-let-group) Group all your `const`s and then group all your `let`s. + + > Why? This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables. ```javascript // bad - var i, len, dragonball, + let i, len, dragonball, items = getItems(), goSportsTeam = true; // bad - var i, items = getItems(), - dragonball, - goSportsTeam = true, - len; + let i; + const items = getItems(); + let dragonball; + const goSportsTeam = true; + let len; // good - var items = getItems(), - goSportsTeam = true, - dragonball, - length, - i; + const goSportsTeam = true; + const items = getItems(); + let dragonball; + let i; + let length; ``` - - Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues. + + - [13.4](#variables--define-where-used) Assign variables where you need them, but place them in a reasonable place. - ```javascript - // bad - function() { - test(); - console.log('doing stuff..'); + > Why? `let` and `const` are block scoped and not function scoped. - //..other stuff.. + ```javascript + // bad - unnecessary function call + function checkName(hasName) { + const name = getName(); - var name = getName(); + if (hasName === 'test') { + return false; + } if (name === 'test') { + this.setName(''); return false; } @@ -421,42 +1394,52 @@ } // good - function() { - var name = getName(); - - test(); - console.log('doing stuff..'); + function checkName(hasName) { + if (hasName === 'test') { + return false; + } - //..other stuff.. + const name = getName(); if (name === 'test') { + this.setName(''); return false; } return name; } + ``` + + - [13.5](#variables--no-chain-assignment) Don't chain variable assignments. - // bad - function() { - var name = getName(); + > Why? Chaining variable assignments creates implicit global variables. - if (!arguments.length) { - return false; - } + ```javascript + // bad + (function example() { + // JavaScript interprets this as + // let a = ( b = ( c = 1 ) ); + // The let keyword only applies to variable a; variables b and c become + // global variables. + let a = b = c = 1; + }()); - return true; - } + console.log(a); // undefined + console.log(b); // 1 + console.log(c); // 1 // good - function() { - if (!arguments.length) { - return false; - } + (function example() { + let a = 1; + let b = a; + let c = a; + }()); - var name = getName(); + console.log(a); // undefined + console.log(b); // undefined + console.log(c); // undefined - return true; - } + // the same applies for `const` ``` **[⬆ back to top](#table-of-contents)** @@ -464,7 +1447,8 @@ ## Hoisting - - Variable declarations get hoisted to the top of their scope, their assignment does not. + + - [14.1](#hoisting--about) `var` declarations get hoisted to the top of their scope, their assignment does not. `const` and `let` declarations are blessed with a new concept called [Temporal Dead Zones (TDZ)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_dead_zone_and_errors_with_let). It's important to know why [typeof is no longer safe](http://es-discourse.com/t/why-typeof-is-no-longer-safe/15). ```javascript // we know this wouldn't work (assuming there @@ -482,17 +1466,25 @@ var declaredButNotAssigned = true; } - // The interpreter is hoisting the variable - // declaration to the top of the scope. - // Which means our example could be rewritten as: + // the interpreter is hoisting the variable + // declaration to the top of the scope, + // which means our example could be rewritten as: function example() { - var declaredButNotAssigned; + let declaredButNotAssigned; console.log(declaredButNotAssigned); // => undefined declaredButNotAssigned = true; } + + // using const and let + function example() { + console.log(declaredButNotAssigned); // => throws a ReferenceError + console.log(typeof declaredButNotAssigned); // => throws a ReferenceError + const declaredButNotAssigned = true; + } ``` - - Anonymous function expressions hoist their variable name, but not the function assignment. + + - [14.2](#hoisting--anon-expressions) Anonymous function expressions hoist their variable name, but not the function assignment. ```javascript function example() { @@ -500,13 +1492,14 @@ anonymous(); // => TypeError anonymous is not a function - var anonymous = function() { + var anonymous = function () { console.log('anonymous function expression'); }; } ``` - - Named function expressions hoist the variable name, not the function name or the function body. + + - [14.3](#hoisting--named-expresions) Named function expressions hoist the variable name, not the function name or the function body. ```javascript function example() { @@ -534,7 +1527,8 @@ } ``` - - Function declarations hoist their name and the function body. + + - [14.4](#hoisting--declarations) Function declarations hoist their name and the function body. ```javascript function example() { @@ -546,16 +1540,18 @@ } ``` - - For more information refer to [JavaScript Scoping & Hoisting](http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting) by [Ben Cherry](http://www.adequatelygood.com/) + - For more information refer to [JavaScript Scoping & Hoisting](http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting/) by [Ben Cherry](http://www.adequatelygood.com/). **[⬆ back to top](#table-of-contents)** +## Comparison Operators & Equality -## Conditional Expressions & Equality + + - [15.1](#comparison--eqeqeq) Use `===` and `!==` over `==` and `!=`. eslint: [`eqeqeq`](http://eslint.org/docs/rules/eqeqeq.html) - - Use `===` and `!==` over `==` and `!=`. - - Conditional expressions are evaluated using coercion with the `ToBoolean` method and always follow these simple rules: + + - [15.2](#comparison--if) 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** + **Undefined** evaluates to **false** @@ -565,13 +1561,14 @@ + **Strings** evaluate to **false** if an empty string `''`, otherwise **true** ```javascript - 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 } ``` - - Use shortcuts. + + - [15.3](#comparison--shortcuts) Use shortcuts. ```javascript // bad @@ -595,7 +1592,95 @@ } ``` - - For more information see [Truth Equality and JavaScript](http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) by Angus Croll + + - [15.4](#comparison--moreinfo) For more information see [Truth Equality and JavaScript](http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) by Angus Croll. + + + - [15.5](#comparison--switch-blocks) 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`](http://eslint.org/docs/rules/no-case-declarations.html). + + ```javascript + // 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](#comparison--nested-ternaries) Ternaries should not be nested and generally be single line expressions. + + eslint rules: [`no-nested-ternary`](http://eslint.org/docs/rules/no-nested-ternary.html). + + ```javascript + // 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](#comparison--unneeded-ternary) Avoid unneeded ternary statements. + + eslint rules: [`no-unneeded-ternary`](http://eslint.org/docs/rules/no-unneeded-ternary.html). + + ```javascript + // 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; + ``` - Else blocks need to start after the closing curly brace of the if @@ -621,7 +1706,8 @@ ## Blocks - - Use braces with all multi-line blocks. + + - [16.1](#blocks--braces) Use braces with all multi-line blocks. ```javascript // bad @@ -637,28 +1723,52 @@ } // bad - function() { return false; } + function foo() { return false; } // good - function() { + function bar() { return false; } ``` + + - [16.2](#blocks--cuddled-elses) 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`](http://eslint.org/docs/rules/brace-style.html) jscs: [`disallowNewlineBeforeBlockStatements`](http://jscs.info/rule/disallowNewlineBeforeBlockStatements) + + ```javascript + // bad + if (test) { + thing1(); + thing2(); + } + else { + thing3(); + } + + // good + if (test) { + thing1(); + thing2(); + } else { + thing3(); + } + ``` + + **[⬆ back to top](#table-of-contents)** ## Comments - - Use `/** ... */` for multiline comments. Include a description, specify types and values for all parameters and return values. + + - [17.1](#comments--multiline) Use `/** ... */` for multi-line comments. ```javascript // bad // make() returns a new element // based on the passed in tag name // - // @param tag - // @return element + // @param {String} tag + // @return {Element} element function make(tag) { // ...stuff... @@ -669,247 +1779,493 @@ // good /** * make() returns a new element - * based on the passed in tag name - * - * @param tag - * @return element + * based on the passed-in tag name */ function make(tag) { // ...stuff... - return element; - } + return element; + } + ``` + + + - [17.2](#comments--singleline) 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. + + ```javascript + // bad + const active = true; // is current tab + + // good + // is current tab + const active = true; + + // bad + function getType() { + console.log('fetching type...'); + // set the default type to 'no type' + const type = this._type || 'no type'; + + return type; + } + + // good + function getType() { + console.log('fetching type...'); + + // set the default type to 'no type' + const type = this._type || 'no type'; + + return type; + } + + // also good + function getType() { + // set the default type to 'no type' + const type = this._type || 'no type'; + + return type; + } + ``` + + + - [17.3](#comments--actionitems) 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](#comments--fixme) Use `// FIXME:` to annotate problems. + + ```javascript + class Calculator extends Abacus { + constructor() { + super(); + + // FIXME: shouldn't use a global here + total = 0; + } + } + ``` + + + - [17.5](#comments--todo) Use `// TODO:` to annotate solutions to problems. + + ```javascript + class Calculator extends Abacus { + constructor() { + super(); + + // TODO: total should be configurable by an options param + this.total = 0; + } + } + ``` + +**[⬆ back to top](#table-of-contents)** + + +## Whitespace + + + - [18.1](#whitespace--spaces) Use soft tabs set to 4 spaces. eslint: [`indent`](http://eslint.org/docs/rules/indent.html) jscs: [`validateIndentation`](http://jscs.info/rule/validateIndentation) + + ```javascript + // good + function foo() { + ∙∙∙∙const name; + } + + // bad + function bar() { + ∙const name; + } + + // bad + function baz() { + ∙∙const name; + } + ``` + + + - [18.2](#whitespace--before-blocks) Place 1 space before the leading brace. eslint: [`space-before-blocks`](http://eslint.org/docs/rules/space-before-blocks.html) jscs: [`requireSpaceBeforeBlockStatements`](http://jscs.info/rule/requireSpaceBeforeBlockStatements) + + ```javascript + // 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](#whitespace--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`](http://eslint.org/docs/rules/keyword-spacing.html) jscs: [`requireSpaceAfterKeywords`](http://jscs.info/rule/requireSpaceAfterKeywords) + + ```javascript + // bad + if(isJedi) { + fight (); + } + + // good + if (isJedi) { + fight(); + } + + // bad + function fight () { + console.log ('Swooosh!'); + } + + // good + function fight() { + console.log('Swooosh!'); + } + ``` + + + - [18.4](#whitespace--infix-ops) Set off operators with spaces. eslint: [`space-infix-ops`](http://eslint.org/docs/rules/space-infix-ops.html) jscs: [`requireSpaceBeforeBinaryOperators`](http://jscs.info/rule/requireSpaceBeforeBinaryOperators), [`requireSpaceAfterBinaryOperators`](http://jscs.info/rule/requireSpaceAfterBinaryOperators) + + ```javascript + // bad + const x=y+5; + + // good + const x = y + 5; + ``` + + + - [18.5](#whitespace--newline-at-end) End files with a single newline character. eslint: [`eol-last`](https://github.com/eslint/eslint/blob/master/docs/rules/eol-last.md) + + ```javascript + // bad + (function (global) { + // ...stuff... + })(this); + ``` + + ```javascript + // bad + (function (global) { + // ...stuff... + })(this);↵ + ↵ + ``` + + ```javascript + // good + (function (global) { + // ...stuff... + })(this);↵ + ``` + + + - [18.6](#whitespace--chains) 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`](http://eslint.org/docs/rules/newline-per-chained-call) [`no-whitespace-before-property`](http://eslint.org/docs/rules/no-whitespace-before-property) + + ```javascript + // 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(); + + // bad + 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); + + // good + 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); + + // good + const leds = stage.selectAll('.led').data(data); ``` - - 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. + + - [18.7](#whitespace--after-blocks) Leave a blank line after blocks and before the next statement. jscs: [`requirePaddingNewLinesAfterBlocks`](http://jscs.info/rule/requirePaddingNewLinesAfterBlocks) ```javascript // bad - var active = true; // is current tab + if (foo) { + return bar; + } + return baz; // good - // is current tab - var active = true; + if (foo) { + return bar; + } - // bad - function getType() { - console.log('fetching type...'); - // set the default type to 'no type' - var type = this._type || 'no type'; + return baz; - return type; - } + // bad + const obj = { + foo() { + }, + bar() { + }, + }; + return obj; // good - function getType() { - console.log('fetching type...'); - - // set the default type to 'no type' - var type = this._type || 'no type'; + const obj = { + foo() { + }, - return type; - } - ``` + bar() { + }, + }; - - 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`. + return obj; - - Use `// FIXME:` to annotate problems + // bad + const arr = [ + function foo() { + }, + function bar() { + }, + ]; + return arr; - ```javascript - function Calculator() { + // good + const arr = [ + function foo() { + }, - // FIXME: shouldn't use a global here - total = 0; + function bar() { + }, + ]; - return this; - } + return arr; ``` - - Use `// TODO:` to annotate solutions to problems + + - [18.8](#whitespace--padded-blocks) Do not pad your blocks with blank lines. eslint: [`padded-blocks`](http://eslint.org/docs/rules/padded-blocks.html) jscs: [`disallowPaddingNewlinesInBlocks`](http://jscs.info/rule/disallowPaddingNewlinesInBlocks) ```javascript - function Calculator() { + // bad + function bar() { - // TODO: total should be configurable by an options param - this.total = 0; + console.log(foo); - return this; } - ``` -**[⬆ back to top](#table-of-contents)** - - -## Whitespace + // also bad + if (baz) { - - Use soft tabs set to 4 spaces - - ```javascript - // bad - function() { - ∙∙var name; - } + console.log(qux); + } else { + console.log(foo); - // bad - function() { - ∙var name; } - // bad - function() { - ∙∙var name; + // good + function bar() { + console.log(foo); } // good - function() { - ∙∙∙∙var name; + if (baz) { + console.log(qux); + } else { + console.log(foo); } ``` - - Place 1 space before the leading brace. + + - [18.9](#whitespace--in-parens) Do not add spaces inside parentheses. eslint: [`space-in-parens`](http://eslint.org/docs/rules/space-in-parens.html) jscs: [`disallowSpacesInsideParentheses`](http://jscs.info/rule/disallowSpacesInsideParentheses) ```javascript // bad - function test(){ - console.log('test'); + function bar( foo ) { + return foo; } // good - function test() { - console.log('test'); + function bar(foo) { + return foo; } // bad - dog.set('attr',{ - age: '1 year', - breed: 'Bernese Mountain Dog' - }); + if ( foo ) { + console.log(foo); + } // good - dog.set('attr', { - age: '1 year', - breed: 'Bernese Mountain Dog' - }); + if (foo) { + console.log(foo); + } ``` - - Set off operators with spaces. + + - [18.10](#whitespace--in-brackets) Do not add spaces inside brackets. eslint: [`array-bracket-spacing`](http://eslint.org/docs/rules/array-bracket-spacing.html) jscs: [`disallowSpacesInsideArrayBrackets`](http://jscs.info/rule/disallowSpacesInsideArrayBrackets) ```javascript // bad - var x=y+5; + const foo = [ 1, 2, 3 ]; + console.log(foo[ 0 ]); // good - var x = y + 5; + const foo = [1, 2, 3]; + console.log(foo[0]); ``` - - Place an empty newline at the end of the file. + + - [18.11](#whitespace--in-braces) Add spaces inside curly braces. eslint: [`object-curly-spacing`](http://eslint.org/docs/rules/object-curly-spacing.html) jscs: [`requireSpacesInsideObjectBrackets`](http://jscs.info/rule/requireSpacesInsideObjectBrackets) ```javascript // bad - (function(global) { - // ...stuff... - })(this); - ``` + const foo = {clark: 'kent'}; - ```javascript // good - (function(global) { - // ...stuff... - })(this); - + const foo = { clark: 'kent' }; ``` - - Use indentation when making long method chains. + + - [18.12](#whitespace--max-len) Avoid having lines of code that are longer than 100 characters (including whitespace). Note: per [above](#strings--line-length), long strings are exempt from this rule, and should not be broken up. eslint: [`max-len`](http://eslint.org/docs/rules/max-len.html) jscs: [`maximumLineLength`](http://jscs.info/rule/maximumLineLength) + + > Why? This ensures readability and maintainability. ```javascript // bad - $('#items').find('.selected').highlight().end().find('.open').updateCount(); - - // good - $('#items') - .find('.selected') - .highlight() - .end() - .find('.open') - .updateCount(); + const foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy; // bad - var leds = stage.selectAll('.led').data(data).enter().append('svg:svg').class('led', true) - .attr('width', (radius + margin) * 2).append('svg:g') - .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')') - .call(tron.led); + $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.')); // good - var leds = stage.selectAll('.led') - .data(data) - .enter().append('svg:svg') - .class('led', true) - .attr('width', (radius + margin) * 2) - .append('svg:g') - .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')') - .call(tron.led); + const foo = jsonData + && jsonData.foo + && jsonData.foo.bar + && jsonData.foo.bar.baz + && jsonData.foo.bar.baz.quux + && jsonData.foo.bar.baz.quux.xyzzy; + + // 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](#table-of-contents)** ## Commas - - Leading commas: **Nope.** + + - [19.1](#commas--leading-trailing) Leading commas: **Nope.** eslint: [`comma-style`](http://eslint.org/docs/rules/comma-style.html) jscs: [`requireCommaBeforeLineBreak`](http://jscs.info/rule/requireCommaBeforeLineBreak) ```javascript // bad - var once + const story = [ + once , upon - , aTime; + , aTime + ]; // good - var once, - upon, - aTime; + const story = [ + once, + upon, + aTime, + ]; // bad - var hero = { - firstName: 'Bob' - , lastName: 'Parr' - , heroName: 'Mr. Incredible' - , superPower: 'strength' + const hero = { + firstName: 'Ada' + , lastName: 'Lovelace' + , birthYear: 1815 + , superPower: 'computers' }; // good - var hero = { - firstName: 'Bob', - lastName: 'Parr', - heroName: 'Mr. Incredible', - superPower: 'strength' + const hero = { + firstName: 'Ada', + lastName: 'Lovelace', + birthYear: 1815, + superPower: 'computers', }; ``` - - Additional trailing comma: **Nope.** This can cause problems with IE6/7 and IE9 if it's in quirksmode. Also, in some implementations of ES3 would add length to an array if it had an additional trailing comma. This was clarified in ES5 ([source](http://es5.github.io/#D)): + + - [19.2](#commas--dangling) Additional trailing comma: **Yup.** eslint: [`comma-dangle`](http://eslint.org/docs/rules/comma-dangle.html) jscs: [`requireTrailingComma`](http://jscs.info/rule/requireTrailingComma) - > Edition 5 clarifies the fact that a trailing comma at the end of an ArrayInitialiser does not add to the length of the array. This is not a semantic change from Edition 3 but some implementations may have previously misinterpreted this. + > 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](es5/README.md#commas) in legacy browsers. ```javascript + // bad - git diff without trailing comma + const hero = { + firstName: 'Florence', + - lastName: 'Nightingale' + + 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 - var hero = { - firstName: 'Kevin', - lastName: 'Flynn', + const hero = { + firstName: 'Dana', + lastName: 'Scully' }; - var heroes = [ + const heroes = [ 'Batman', - 'Superman', + 'Superman' ]; // good - var hero = { - firstName: 'Kevin', - lastName: 'Flynn' + const hero = { + firstName: 'Dana', + lastName: 'Scully', }; - var heroes = [ + const heroes = [ 'Batman', - 'Superman' + 'Superman', ]; ``` @@ -918,78 +2274,82 @@ ## Semicolons - - **Yup.** + + - [20.1](#20.1) **Yup.** eslint: [`semi`](http://eslint.org/docs/rules/semi.html) jscs: [`requireSemicolons`](http://jscs.info/rule/requireSemicolons) ```javascript // bad - (function() { - var name = 'Skywalker' + (function () { + const name = 'Skywalker' return name })() // good - (function() { - var name = 'Skywalker'; + (function () { + const name = 'Skywalker'; return name; - })(); + }()); - // good - ;(function() { - var name = 'Skywalker'; + // good, but legacy (guards against the function becoming an argument when two files with IIFEs are concatenated) + ;(() => { + const name = 'Skywalker'; return name; - })(); + }()); ``` + [Read more](http://stackoverflow.com/questions/7365172/semicolon-before-self-invoking-function/7365214%237365214). + **[⬆ back to top](#table-of-contents)** ## Type Casting & Coercion - - Perform type coercion at the beginning of the statement. - - Strings: + + - [21.1](#coercion--explicit) Perform type coercion at the beginning of the statement. + + + - [21.2](#coercion--strings) Strings: ```javascript - // => this.reviewScore = 9; + // => this.reviewScore = 9; // bad - var totalScore = this.reviewScore + ''; - - // good - var totalScore = '' + this.reviewScore; + const totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf() // bad - var totalScore = '' + this.reviewScore + ' total score'; + const totalScore = this.reviewScore.toString(); // isn't guaranteed to return a string // good - var totalScore = this.reviewScore + ' total score'; + const totalScore = String(this.reviewScore); ``` - - Use `parseInt` for Numbers and always with a radix for type casting. + + - [21.3](#coercion--numbers) Numbers: Use `Number` for type casting and `parseInt` always with a radix for parsing strings. eslint: [`radix`](http://eslint.org/docs/rules/radix) ```javascript - var inputValue = '4'; + const inputValue = '4'; // bad - var val = new Number(inputValue); + const val = new Number(inputValue); // bad - var val = +inputValue; + const val = +inputValue; // bad - var val = inputValue >> 0; + const val = inputValue >> 0; // bad - var val = parseInt(inputValue); + const val = parseInt(inputValue); // good - var val = Number(inputValue); + const val = Number(inputValue); // good - var val = parseInt(inputValue, 10); + const val = parseInt(inputValue, 10); ``` - - If for whatever reason you are doing something wild and `parseInt` is your bottleneck and need to use Bitshift for [performance reasons](http://jsperf.com/coercion-vs-casting/3), leave a comment explaining why and what you're doing. - - **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but Bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109) + + - [21.4](#coercion--comment-deviations) If for whatever reason you are doing something wild and `parseInt` is your bottleneck and need to use Bitshift for [performance reasons](http://jsperf.com/coercion-vs-casting/3), leave a comment explaining why and what you're doing. ```javascript // good @@ -998,22 +2358,32 @@ * Bitshifting the String to coerce it to a * Number made it a lot faster. */ - var val = inputValue >> 0; + const val = inputValue >> 0; + ``` + + + - [21.5](#coercion--bitwise) **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647: + + ```javascript + 2147483647 >> 0 //=> 2147483647 + 2147483648 >> 0 //=> -2147483648 + 2147483649 >> 0 //=> -2147483647 ``` - - Booleans: + + - [21.6](#coercion--booleans) Booleans: ```javascript - var age = 0; + const age = 0; // bad - var hasAge = new Boolean(age); + const hasAge = new Boolean(age); // good - var hasAge = Boolean(age); + const hasAge = Boolean(age); - // good - var hasAge = !!age; + // best + const hasAge = !!age; ``` **[⬆ back to top](#table-of-contents)** @@ -1021,7 +2391,8 @@ ## Naming Conventions - - Avoid single letter names. Be descriptive with your naming. + + - [22.1](#naming--descriptive) Avoid single letter names. Be descriptive with your naming. eslint: [`id-length`](http://eslint.org/docs/rules/id-length) ```javascript // bad @@ -1035,26 +2406,22 @@ } ``` - - Use camelCase when naming objects, functions, and instances + + - [22.2](#naming--camelCase) Use camelCase when naming objects, functions, and instances. eslint: [`camelcase`](http://eslint.org/docs/rules/camelcase.html) jscs: [`requireCamelCaseOrUpperCaseIdentifiers`](http://jscs.info/rule/requireCamelCaseOrUpperCaseIdentifiers) ```javascript // bad - var OBJEcttsssss = {}; - var this_is_my_object = {}; - function c() {}; - var u = new user({ - name: 'Bob Parr' - }); + const OBJEcttsssss = {}; + const this_is_my_object = {}; + function c() {} // good - var thisIsMyObject = {}; - function thisIsMyFunction() {}; - var user = new User({ - name: 'Bob Parr' - }); + const thisIsMyObject = {}; + function thisIsMyFunction() {} ``` - - Use PascalCase when naming constructors or classes + + - [22.3](#naming--PascalCase) Use PascalCase only when naming constructors or classes. eslint: [`new-cap`](http://eslint.org/docs/rules/new-cap.html) jscs: [`requireCapitalizedConstructors`](http://jscs.info/rule/requireCapitalizedConstructors) ```javascript // bad @@ -1062,55 +2429,61 @@ this.name = options.name; } - var bad = new user({ - name: 'nope' + const bad = new user({ + name: 'nope', }); // good - function User(options) { - this.name = options.name; + class User { + constructor(options) { + this.name = options.name; + } } - var good = new User({ - name: 'yup' + const good = new User({ + name: 'yup', }); ``` - - Use a leading underscore `_` when naming private properties + + - [22.4](#naming--leading-underscore) Do not use trailing or leading underscores. eslint: [`no-underscore-dangle`](http://eslint.org/docs/rules/no-underscore-dangle.html) jscs: [`disallowDanglingUnderscores`](http://jscs.info/rule/disallowDanglingUnderscores) + + > Why? JavaScript does not have the concept of privacy in terms of properties or methods. Although a leading underscore is a common convention to mean “private”, in fact, these properties are fully public, and as such, are part of your public API contract. This convention might lead developers to wrongly think that a change won't count as breaking, or that tests aren't needed. tl;dr: if you want something to be “private”, it must not be observably present. ```javascript // bad this.__firstName__ = 'Panda'; this.firstName_ = 'Panda'; + this._firstName = 'Panda'; // good - this._firstName = 'Panda'; + this.firstName = 'Panda'; ``` - - When saving a reference to `this` use `_this`. Never use `Function#bind(this)` if the closure is available. \[[jsperf](http://jsperf.com/bind-vs-jquery-proxy/60)\] + + - [22.5](#naming--self-this) Don't save references to `this`. Use arrow functions or [Function#bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). jscs: [`disallowNodeTypes`](http://jscs.info/rule/disallowNodeTypes) ```javascript // bad - function() { - var self = this; - return function() { + function foo() { + const self = this; + return function () { console.log(self); }; } // bad - function() { - var that = this; - return function() { + function foo() { + const that = this; + return function () { console.log(that); }; } // good - function() { - var _this = this; - return function() { - console.log(_this); + function foo() { + return () => { + console.log(this); }; } @@ -1122,157 +2495,133 @@ } ``` - - Name your functions. This is helpful for stack traces. + + - [22.6](#naming--filename-matches-export) A base filename should exactly match the name of its default export. ```javascript - // bad - var log = function(msg) { - console.log(msg); - }; - - // good - var log = function log(msg) { - console.log(msg); - }; - ``` - -**[⬆ back to top](#table-of-contents)** - + // file 1 contents + class CheckBox { + // ... + } + export default CheckBox; -## Accessors + // file 2 contents + export default function fortyTwo() { return 42; } - - Accessor functions for properties are not required - - If you do make accessor functions use getVal() and setVal('hello') + // file 3 contents + export default function insideDirectory() {} - ```javascript + // in some other file // bad - dragon.age(); - - // good - dragon.getAge(); + import CheckBox from './checkBox'; // PascalCase import/export, camelCase filename + import FortyTwo from './FortyTwo'; // PascalCase import/filename, camelCase export + import InsideDirectory from './InsideDirectory'; // PascalCase import/filename, camelCase export // bad - dragon.age(25); + import CheckBox from './check_box'; // PascalCase import/export, snake_case filename + import forty_two from './forty_two'; // snake_case import/filename, camelCase export + import inside_directory from './inside_directory'; // snake_case import, camelCase export + import index from './inside_directory/index'; // requiring the index file explicitly + import insideDirectory from './insideDirectory/index'; // requiring the index file explicitly // good - dragon.setAge(25); + import CheckBox from './CheckBox'; // PascalCase export/import/filename + import fortyTwo from './fortyTwo'; // camelCase export/import/filename + import insideDirectory from './insideDirectory'; // camelCase export/import/directory name/implicit "index" + // ^ supports both insideDirectory.js and insideDirectory/index.js ``` - - If the property is a boolean, use isVal() or hasVal() + + - [22.7](#naming--camelCase-default-export) Use camelCase when you export-default a function. Your filename should be identical to your function's name. ```javascript - // bad - if (!dragon.age()) { - return false; + function makeStyleGuide() { } - // good - if (!dragon.hasAge()) { - return false; - } + export default makeStyleGuide; ``` - - It's okay to create get() and set() functions, but be consistent. + + - [22.8](#naming--PascalCase-singleton) Use PascalCase when you export a constructor / class / singleton / function library / bare object. ```javascript - function Jedi(options) { - options || (options = {}); - var lightsaber = options.lightsaber || 'blue'; - this.set('lightsaber', lightsaber); - } - - Jedi.prototype.set = function(key, val) { - this[key] = val; + const AirbnbStyleGuide = { + es6: { + } }; - Jedi.prototype.get = function(key) { - return this[key]; - }; + export default AirbnbStyleGuide; ``` + **[⬆ back to top](#table-of-contents)** -## Constructors +## Accessors + + + - [23.1](#accessors--not-required) Accessor functions for properties are not required. - - Assign methods to the prototype object, instead of overwriting the prototype with a new object. Overwriting the prototype makes inheritance impossible: by resetting the prototype you'll overwrite the base! + + - [23.2](#accessors--no-getters-setters) Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use getVal() and setVal('hello'). ```javascript - function Jedi() { - console.log('new jedi'); - } - // bad - Jedi.prototype = { - fight: function fight() { - console.log('fighting'); - }, + class Dragon { + get age() { + // ... + } - block: function block() { - console.log('blocking'); + set age(value) { + // ... } - }; + } // good - Jedi.prototype.fight = function fight() { - console.log('fighting'); - }; + class Dragon { + getAge() { + // ... + } - Jedi.prototype.block = function block() { - console.log('blocking'); - }; + setAge(value) { + // ... + } + } ``` - - Methods can return `this` to help with method chaining. + + - [23.3](#accessors--boolean-prefix) If the property/method is a `boolean`, use `isVal()` or `hasVal()`. ```javascript // bad - Jedi.prototype.jump = function() { - this.jumping = true; - return true; - }; - - Jedi.prototype.setHeight = function(height) { - this.height = height; - }; - - var luke = new Jedi(); - luke.jump(); // => true - luke.setHeight(20) // => undefined + if (!dragon.age()) { + return false; + } // good - Jedi.prototype.jump = function() { - this.jumping = true; - return this; - }; - - Jedi.prototype.setHeight = function(height) { - this.height = height; - return this; - }; - - var luke = new Jedi(); - - luke.jump() - .setHeight(20); + if (!dragon.hasAge()) { + return false; + } ``` - - - It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects. + + - [23.4](#accessors--consistent) It's okay to create get() and set() functions, but be consistent. ```javascript - function Jedi(options) { - options || (options = {}); - this.name = options.name || 'no name'; - } + class Jedi { + constructor(options = {}) { + const lightsaber = options.lightsaber || 'blue'; + this.set('lightsaber', lightsaber); + } - Jedi.prototype.getName = function getName() { - return this.name; - }; + set(key, val) { + this[key] = val; + } - Jedi.prototype.toString = function toString() { - return 'Jedi - ' + this.getName(); - }; + get(key) { + return this[key]; + } + } ``` **[⬆ back to top](#table-of-contents)** @@ -1280,28 +2629,29 @@ ## Events - - When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of: + + - [24.1](#events--hash) When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of: - ```js + ```javascript // bad $(this).trigger('listingUpdated', listing.id); ... - $(this).on('listingUpdated', function(e, listingId) { + $(this).on('listingUpdated', (e, listingId) => { // do something with listingId }); ``` prefer: - ```js + ```javascript // good - $(this).trigger('listingUpdated', { listingId : listing.id }); + $(this).trigger('listingUpdated', { listingId: listing.id }); ... - $(this).on('listingUpdated', function(e, data) { + $(this).on('listingUpdated', (e, data) => { // do something with data.listingId }); ``` @@ -1309,38 +2659,6 @@ **[⬆ back to top](#table-of-contents)** -## Modules - -** Note: ** We can ignore this section since the ES6 transpiler adds 'use strict' for us, doesn't require the trailing `!` and ember forces us to use dashs for file names. - - - The module should start with a `!`. This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated. [Explanation](https://github.com/airbnb/javascript/issues/44#issuecomment-13063933) - - The file should be named-with-dashes, live in a folder with the same name, and match the name of the single export. - - Add a method called noConflict() that sets the exported module to the previous version and returns this one. - - Always declare `'use strict';` at the top of the module. - - ```javascript - // fancy-input/fancy-input.js - - !function(global) { - 'use strict'; - - var previousFancyInput = global.FancyInput; - - function FancyInput(options) { - this.options = options || {}; - } - - FancyInput.noConflict = function noConflict() { - global.FancyInput = previousFancyInput; - return FancyInput; - }; - - global.FancyInput = FancyInput; - }(this); - ``` - -**[⬆ back to top](#table-of-contents)** - ## File Names ** Note: ** this section isn't part of the original AirBnB guide. @@ -1367,68 +2685,73 @@ function foo(...args) { ## Destructuring -** Note: ** this section isn't part of the original AirBnB guide. It comes from [Ember's Styleguide](https://github.com/emberjs/ember.js/blob/master/STYLEGUIDE.md) + ** Note: ** this section isn't part of the original AirBnB guide. It comes from [Ember's Styleguide](https://github.com/emberjs/ember.js/blob/master/STYLEGUIDE.md) -When decomposing simple arrays or objects, prefer [destructuring](http://babeljs.io/docs/learn-es6/#destructuring). + When decomposing simple arrays or objects, prefer [destructuring](http://babeljs.io/docs/learn-es6/#destructuring). -```javascript -// array destructuring -var fullName = 'component:foo-bar'; -var [ - first, - last -] = fullName.split(':'); -``` + ```javascript + // array destructuring + var fullName = 'component:foo-bar'; + var [ + first, + last + ] = fullName.split(':'); + ``` -```javascript -// object destructuring -var person = { - firstName: 'Stefan', - lastName: 'Penner' -}; - -var { - firstName, - lastName -} = person; -``` + ```javascript + // object destructuring + var person = { + firstName: 'Stefan', + lastName: 'Penner' + }; + + var { + firstName, + lastName + } = person; + ``` **[⬆ back to top](#table-of-contents)** ## Comments -** Note: ** this section isn't part of the original AirBnB guide. It comes from [Ember's Styleguide](https://github.com/emberjs/ember.js/blob/master/STYLEGUIDE.md) + ** Note: ** this section isn't part of the original AirBnB guide. It comes from [Ember's Styleguide](https://github.com/emberjs/ember.js/blob/master/STYLEGUIDE.md) -+ Use [YUIDoc](http://yui.github.io/yuidoc/syntax/index.html) comments for - documenting functions. -+ Use `//` for single line comments. + + Use [YUIDoc](http://yui.github.io/yuidoc/syntax/index.html) comments for + documenting functions. + + Use `//` for single line comments. -```javascript -function foo() { - var bar = 5; + ```javascript + function foo() { + var bar = 5; - // multiplies `bar` by 2. - fooBar(bar); + // multiplies `bar` by 2. + fooBar(bar); - console.log(bar); -} -``` + console.log(bar); + } + ``` **[⬆ back to top](#table-of-contents)** ## jQuery - - Prefix jQuery object variables with a `$`. + + - [25.1](#jquery--dollar-prefix) Prefix jQuery object variables with a `$`. jscs: [`requireDollarBeforejQueryAssignment`](http://jscs.info/rule/requireDollarBeforejQueryAssignment) ```javascript // bad - var sidebar = $('.sidebar'); + const sidebar = $('.sidebar'); + + // good + const $sidebar = $('.sidebar'); // good - var $sidebar = $('.sidebar'); + const $sidebarBtn = $('.sidebar-btn'); ``` - - Cache jQuery lookups. + + - [25.2](#jquery--cache) Cache jQuery lookups. ```javascript // bad @@ -1444,7 +2767,7 @@ function foo() { // good function setSidebar() { - var $sidebar = $('.sidebar'); + const $sidebar = $('.sidebar'); $sidebar.hide(); // ...stuff... @@ -1455,8 +2778,11 @@ function foo() { } ``` - - For DOM queries use Cascading `$('.sidebar ul')` or parent > child `$('.sidebar > ul')`. [jsPerf](http://jsperf.com/jquery-find-vs-context-sel/16) - - Use `find` with scoped jQuery object queries. + + - [25.3](#jquery--queries) For DOM queries use Cascading `$('.sidebar ul')` or parent > child `$('.sidebar > ul')`. [jsPerf](http://jsperf.com/jquery-find-vs-context-sel/16) + + + - [25.4](#jquery--find) Use `find` with scoped jQuery object queries. ```javascript // bad @@ -1480,33 +2806,65 @@ function foo() { ## ECMAScript 5 Compatibility - - Refer to [Kangax](https://twitter.com/kangax/)'s ES5 [compatibility table](http://kangax.github.com/es5-compat-table/) + + - [26.1](#es5-compat--kangax) Refer to [Kangax](https://twitter.com/kangax/)'s ES5 [compatibility table](http://kangax.github.io/es5-compat-table/). **[⬆ back to top](#table-of-contents)** +## ECMAScript 6 Styles + + + - [27.1](#es6-styles) This is a collection of links to the various ES6 features. + +1. [Arrow Functions](#arrow-functions) +1. [Classes](#constructors) +1. [Object Shorthand](#es6-object-shorthand) +1. [Object Concise](#es6-object-concise) +1. [Object Computed Properties](#es6-computed-properties) +1. [Template Strings](#es6-template-literals) +1. [Destructuring](#destructuring) +1. [Default Parameters](#es6-default-parameters) +1. [Rest](#es6-rest) +1. [Array Spreads](#es6-array-spreads) +1. [Let and Const](#references) +1. [Iterators and Generators](#iterators-and-generators) +1. [Modules](#modules) + +**[⬆ back to top](#table-of-contents)** ## Testing - - **Yup.** + + - [28.1](#testing--yup) **Yup.** ```javascript - function() { + function foo() { return true; } ``` + + - [28.2](#testing--for-real) **No, but seriously**: + - Whichever testing framework you use, you should be writing tests! + - Strive to write many small pure functions, and minimize where mutations occur. + - Be cautious about stubs and mocks - they can make your tests more brittle. + - We primarily use [`mocha`](https://www.npmjs.com/package/mocha) at Airbnb. [`tape`](https://www.npmjs.com/package/tape) is also used occasionally for small, separate modules. + - 100% test coverage is a good goal to strive for, even if it's not always practical to reach it. + - Whenever you fix a bug, _write a regression test_. A bug fixed without a regression test is almost certainly going to break again in the future. + **[⬆ back to top](#table-of-contents)** ## Performance - - [On Layout & Web Performance](http://kellegous.com/j/2013/01/26/layout-performance/) + - [On Layout & Web Performance](http://www.kellegous.com/j/2013/01/26/layout-performance/) - [String vs Array Concat](http://jsperf.com/string-vs-array-concat/2) - [Try/Catch Cost In a Loop](http://jsperf.com/try-catch-in-loop-cost) - [Bang Function](http://jsperf.com/bang-function) - [jQuery Find vs Context, Selector](http://jsperf.com/jquery-find-vs-context-sel/13) - [innerHTML vs textContent for script text](http://jsperf.com/innerhtml-vs-textcontent-for-script-text) - [Long String Concatenation](http://jsperf.com/ya-string-concat) + - [Are Javascript functions like `map()`, `reduce()`, and `filter()` optimized for traversing arrays?](https://www.quora.com/JavaScript-programming-language-Are-Javascript-functions-like-map-reduce-and-filter-already-optimized-for-traversing-array/answer/Quildreen-Motta) - Loading... **[⬆ back to top](#table-of-contents)** @@ -1514,22 +2872,36 @@ function foo() { ## Resources +**Learning ES6** + + - [Draft ECMA 2015 (ES6) Spec](https://people.mozilla.org/~jorendorff/es6-draft.html) + - [ExploringJS](http://exploringjs.com/) + - [ES6 Compatibility Table](https://kangax.github.io/compat-table/es6/) + - [Comprehensive Overview of ES6 Features](http://es6-features.org/) **Read This** - - [Annotated ECMAScript 5.1](http://es5.github.com/) + - [Standard ECMA-262](http://www.ecma-international.org/ecma-262/6.0/index.html) + +**Tools** -**Other Styleguides** + - Code Style Linters + + [ESlint](http://eslint.org/) - [Airbnb Style .eslintrc](https://github.com/airbnb/javascript/blob/master/linters/.eslintrc) + + [JSHint](http://jshint.com/) - [Airbnb Style .jshintrc](https://github.com/airbnb/javascript/blob/master/linters/.jshintrc) + + [JSCS](https://github.com/jscs-dev/node-jscs) - [Airbnb Style Preset](https://github.com/jscs-dev/node-jscs/blob/master/presets/airbnb.json) - - [Google JavaScript Style Guide](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml) - - [jQuery Core Style Guidelines](http://docs.jquery.com/JQuery_Core_Style_Guidelines) - - [Principles of Writing Consistent, Idiomatic JavaScript](https://github.com/rwldrn/idiomatic.js/) +**Other Style Guides** + + - [Google JavaScript Style Guide](https://google.github.io/styleguide/javascriptguide.xml) + - [jQuery Core Style Guidelines](http://contribute.jquery.org/style-guide/js/) + - [Principles of Writing Consistent, Idiomatic JavaScript](https://github.com/rwaldron/idiomatic.js) **Other Styles** - - [Naming this in nested functions](https://gist.github.com/4135065) - Christian Johansen - - [Conditional Callbacks](https://github.com/airbnb/javascript/issues/52) - - [Popular JavaScript Coding Conventions on Github](http://sideeffect.kr/popularconvention/#javascript) + - [Naming this in nested functions](https://gist.github.com/cjohansen/4135065) - Christian Johansen + - [Conditional Callbacks](https://github.com/airbnb/javascript/issues/52) - Ross Allen + - [Popular JavaScript Coding Conventions on Github](http://sideeffect.kr/popularconvention/#javascript) - JeongHoon Byun + - [Multiple var statements in JavaScript, not superfluous](http://benalman.com/news/2012/05/multiple-var-statements-javascript/) - Ben Alman **Further Reading** @@ -1537,6 +2909,7 @@ function foo() { - [Basic JavaScript for the impatient programmer](http://www.2ality.com/2013/06/basic-javascript.html) - Dr. Axel Rauschmayer - [You Might Not Need jQuery](http://youmightnotneedjquery.com/) - Zack Bloom & Adam Schwartz - [ES6 Features](https://github.com/lukehoban/es6features) - Luke Hoban + - [Frontend Guidelines](https://github.com/bendc/frontend-guidelines) - Benjamin De Cock **Books** @@ -1551,70 +2924,134 @@ function foo() { - [Secrets of the JavaScript Ninja](http://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/193398869X) - John Resig and Bear Bibeault - [Human JavaScript](http://humanjavascript.com/) - Henrik Joreteg - [Superhero.js](http://superherojs.com/) - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy - - [JSBooks](http://jsbooks.revolunet.com/) - - [Third Party JavaScript](http://manning.com/vinegar/) - Ben Vinegar and Anton Kovalyov + - [JSBooks](http://jsbooks.revolunet.com/) - Julien Bouquillon + - [Third Party JavaScript](https://www.manning.com/books/third-party-javascript) - Ben Vinegar and Anton Kovalyov + - [Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript](http://amzn.com/0321812182) - David Herman + - [Eloquent JavaScript](http://eloquentjavascript.net/) - Marijn Haverbeke + - [You Don't Know JS: ES6 & Beyond](http://shop.oreilly.com/product/0636920033769.do) - Kyle Simpson **Blogs** - [DailyJS](http://dailyjs.com/) - [JavaScript Weekly](http://javascriptweekly.com/) - [JavaScript, JavaScript...](http://javascriptweblog.wordpress.com/) - - [Bocoup Weblog](http://weblog.bocoup.com/) + - [Bocoup Weblog](https://bocoup.com/weblog) - [Adequately Good](http://www.adequatelygood.com/) - - [NCZOnline](http://www.nczonline.net/) + - [NCZOnline](https://www.nczonline.net/) - [Perfection Kills](http://perfectionkills.com/) - [Ben Alman](http://benalman.com/) - [Dmitry Baranovskiy](http://dmitry.baranovskiy.com/) - [Dustin Diaz](http://dustindiaz.com/) - - [nettuts](http://net.tutsplus.com/?s=javascript) + - [nettuts](http://code.tutsplus.com/?s=javascript) + +**Podcasts** + + - [JavaScript Jabber](https://devchat.tv/js-jabber/) + **[⬆ back to top](#table-of-contents)** ## In the Wild - This is a list of organizations that are using this style guide. Send us a pull request or open an issue and we'll add you to the list. + This is a list of organizations that are using this style guide. Send us a pull request and we'll add you to the list. + - **4Catalyzer**: [4Catalyzer/javascript](https://github.com/4Catalyzer/javascript) - **Aan Zee**: [AanZee/javascript](https://github.com/AanZee/javascript) + - **Adult Swim**: [adult-swim/javascript](https://github.com/adult-swim/javascript) - **Airbnb**: [airbnb/javascript](https://github.com/airbnb/javascript) - - **American Insitutes for Research**: [AIRAST/javascript](https://github.com/AIRAST/javascript) + - **Apartmint**: [apartmint/javascript](https://github.com/apartmint/javascript) + - **Ascribe**: [ascribe/javascript](https://github.com/ascribe/javascript) + - **Avalara**: [avalara/javascript](https://github.com/avalara/javascript) + - **Avant**: [avantcredit/javascript](https://github.com/avantcredit/javascript) + - **Billabong**: [billabong/javascript](https://github.com/billabong/javascript) + - **Bisk**: [bisk/javascript](https://github.com/Bisk/javascript/) + - **Blendle**: [blendle/javascript](https://github.com/blendle/javascript) + - **Brainshark**: [brainshark/javascript](https://github.com/brainshark/javascript) + - **Chartboost**: [ChartBoost/javascript-style-guide](https://github.com/ChartBoost/javascript-style-guide) + - **ComparaOnline**: [comparaonline/javascript](https://github.com/comparaonline/javascript-style-guide) - **Compass Learning**: [compasslearning/javascript-style-guide](https://github.com/compasslearning/javascript-style-guide) + - **DailyMotion**: [dailymotion/javascript](https://github.com/dailymotion/javascript) + - **DoSomething**: [DoSomething/eslint-config](https://github.com/DoSomething/eslint-config) - **Digitpaint** [digitpaint/javascript](https://github.com/digitpaint/javascript) + - **Ecosia**: [ecosia/javascript](https://github.com/ecosia/javascript) + - **Evernote**: [evernote/javascript-style-guide](https://github.com/evernote/javascript-style-guide) + - **Evolution Gaming**: [evolution-gaming/javascript](https://github.com/evolution-gaming/javascript) + - **EvozonJs**: [evozonjs/javascript](https://github.com/evozonjs/javascript) - **ExactTarget**: [ExactTarget/javascript](https://github.com/ExactTarget/javascript) + - **Expensify** [Expensify/Style-Guide](https://github.com/Expensify/Style-Guide/blob/master/javascript.md) + - **Flexberry**: [Flexberry/javascript-style-guide](https://github.com/Flexberry/javascript-style-guide) - **Gawker Media**: [gawkermedia/javascript](https://github.com/gawkermedia/javascript) - - **GeneralElectric**: [GeneralElectric/javascript](https://github.com/GeneralElectric/javascript) + - **General Electric**: [GeneralElectric/javascript](https://github.com/GeneralElectric/javascript) - **GoodData**: [gooddata/gdc-js-style](https://github.com/gooddata/gdc-js-style) - **Grooveshark**: [grooveshark/javascript](https://github.com/grooveshark/javascript) - - **How About We**: [howaboutwe/javascript](https://github.com/howaboutwe/javascript) + - **How About We**: [howaboutwe/javascript](https://github.com/howaboutwe/javascript-style-guide) + - **Huballin**: [huballin/javascript](https://github.com/huballin/javascript) + - **HubSpot**: [HubSpot/javascript](https://github.com/HubSpot/javascript) + - **Hyper**: [hyperoslo/javascript-playbook](https://github.com/hyperoslo/javascript-playbook/blob/master/style.md) + - **InfoJobs**: [InfoJobs/JavaScript-Style-Guide](https://github.com/InfoJobs/JavaScript-Style-Guide) + - **Intent Media**: [intentmedia/javascript](https://github.com/intentmedia/javascript) + - **Jam3**: [Jam3/Javascript-Code-Conventions](https://github.com/Jam3/Javascript-Code-Conventions) + - **JeopardyBot**: [kesne/jeopardy-bot](https://github.com/kesne/jeopardy-bot/blob/master/STYLEGUIDE.md) + - **JSSolutions**: [JSSolutions/javascript](https://github.com/JSSolutions/javascript) + - **KickorStick**: [kickorstick/javascript](https://github.com/kickorstick/javascript) + - **Kinetica Solutions**: [kinetica/javascript](https://github.com/kinetica/Javascript-style-guide) + - **M2GEN**: [M2GEN/javascript](https://github.com/M2GEN/javascript) - **Mighty Spring**: [mightyspring/javascript](https://github.com/mightyspring/javascript) - **MinnPost**: [MinnPost/javascript](https://github.com/MinnPost/javascript) + - **MitocGroup**: [MitocGroup/javascript](https://github.com/MitocGroup/javascript) - **ModCloth**: [modcloth/javascript](https://github.com/modcloth/javascript) - **Money Advice Service**: [moneyadviceservice/javascript](https://github.com/moneyadviceservice/javascript) + - **Muber**: [muber/javascript](https://github.com/muber/javascript) - **National Geographic**: [natgeo/javascript](https://github.com/natgeo/javascript) - **National Park Service**: [nationalparkservice/javascript](https://github.com/nationalparkservice/javascript) + - **Nimbl3**: [nimbl3/javascript](https://github.com/nimbl3/javascript) - **Orion Health**: [orionhealth/javascript](https://github.com/orionhealth/javascript) + - **OutBoxSoft**: [OutBoxSoft/javascript](https://github.com/OutBoxSoft/javascript) - **Peerby**: [Peerby/javascript](https://github.com/Peerby/javascript) - **Razorfish**: [razorfish/javascript-style-guide](https://github.com/razorfish/javascript-style-guide) - - **SeekingAlpha**: [seekingalpha/javascript-style-guide](https://github.com/seekingalpha/javascript-style-guide) - - **REI**: [reidev/js-style-guide](https://github.com/reidev/js-style-guide) + - **reddit**: [reddit/styleguide/javascript](https://github.com/reddit/styleguide/tree/master/javascript) + - **React**: [/facebook/react/blob/master/CONTRIBUTING.md#style-guide](https://github.com/facebook/react/blob/master/CONTRIBUTING.md#style-guide) + - **REI**: [reidev/js-style-guide](https://github.com/rei/code-style-guides/blob/master/docs/javascript.md) - **Ripple**: [ripple/javascript-style-guide](https://github.com/ripple/javascript-style-guide) + - **SeekingAlpha**: [seekingalpha/javascript-style-guide](https://github.com/seekingalpha/javascript-style-guide) - **Shutterfly**: [shutterfly/javascript](https://github.com/shutterfly/javascript) - - **Userify**: [userify/javascript](https://github.com/userify/javascript) + - **Springload**: [springload/javascript](https://github.com/springload/javascript) + - **StratoDem Analytics**: [stratodem/javascript](https://github.com/stratodem/javascript) + - **SteelKiwi Development**: [steelkiwi/javascript](https://github.com/steelkiwi/javascript) + - **StudentSphere**: [studentsphere/javascript](https://github.com/studentsphere/guide-javascript) + - **SysGarage**: [sysgarage/javascript-style-guide](https://github.com/sysgarage/javascript-style-guide) + - **Syzygy Warsaw**: [syzygypl/javascript](https://github.com/syzygypl/javascript) + - **Target**: [target/javascript](https://github.com/target/javascript) + - **TheLadders**: [TheLadders/javascript](https://github.com/TheLadders/javascript) + - **The Nerdery**: [thenerdery/javascript-standards](https://github.com/thenerdery/javascript-standards) + - **T4R Technology**: [T4R-Technology/javascript](https://github.com/T4R-Technology/javascript) + - **VoxFeed**: [VoxFeed/javascript-style-guide](https://github.com/VoxFeed/javascript-style-guide) + - **WeBox Studio**: [weboxstudio/javascript](https://github.com/weboxstudio/javascript) + - **Weggo**: [Weggo/javascript](https://github.com/Weggo/javascript) - **Zillow**: [zillow/javascript](https://github.com/zillow/javascript) - **ZocDoc**: [ZocDoc/javascript](https://github.com/ZocDoc/javascript) +**[⬆ back to top](#table-of-contents)** + ## Translation This style guide is also available in other languages: - - :de: **German**: [timofurrer/javascript-style-guide](https://github.com/timofurrer/javascript-style-guide) - - :jp: **Japanese**: [mitsuruog/javacript-style-guide](https://github.com/mitsuruog/javacript-style-guide) - - :br: **Portuguese**: [armoucar/javascript-style-guide](https://github.com/armoucar/javascript-style-guide) - - :cn: **Chinese**: [adamlu/javascript-style-guide](https://github.com/adamlu/javascript-style-guide) - - :es: **Spanish**: [paolocarrasco/javascript-style-guide](https://github.com/paolocarrasco/javascript-style-guide) - - :kr: **Korean**: [tipjs/javascript-style-guide](https://github.com/tipjs/javascript-style-guide) - - :fr: **French**: [nmussy/javascript-style-guide](https://github.com/nmussy/javascript-style-guide) - - :ru: **Russian**: [uprock/javascript](https://github.com/uprock/javascript) - - :bg: **Bulgarian**: [borislavvv/javascript](https://github.com/borislavvv/javascript) + - ![br](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Brazil.png) **Brazilian Portuguese**: [armoucar/javascript-style-guide](https://github.com/armoucar/javascript-style-guide) + - ![bg](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Bulgaria.png) **Bulgarian**: [borislavvv/javascript](https://github.com/borislavvv/javascript) + - ![ca](https://raw.githubusercontent.com/fpmweb/javascript-style-guide/master/img/catala.png) **Catalan**: [fpmweb/javascript-style-guide](https://github.com/fpmweb/javascript-style-guide) + - ![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png) **Chinese (Simplified)**: [sivan/javascript-style-guide](https://github.com/sivan/javascript-style-guide) + - ![tw](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Taiwan.png) **Chinese (Traditional)**: [jigsawye/javascript](https://github.com/jigsawye/javascript) + - ![fr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/France.png) **French**: [nmussy/javascript-style-guide](https://github.com/nmussy/javascript-style-guide) + - ![de](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Germany.png) **German**: [timofurrer/javascript-style-guide](https://github.com/timofurrer/javascript-style-guide) + - ![it](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Italy.png) **Italian**: [sinkswim/javascript-style-guide](https://github.com/sinkswim/javascript-style-guide) + - ![jp](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Japan.png) **Japanese**: [mitsuruog/javascript-style-guide](https://github.com/mitsuruog/javascript-style-guide) + - ![kr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/South-Korea.png) **Korean**: [tipjs/javascript-style-guide](https://github.com/tipjs/javascript-style-guide) + - ![pl](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Poland.png) **Polish**: [mjurczyk/javascript](https://github.com/mjurczyk/javascript) + - ![ru](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Russia.png) **Russian**: [uprock/javascript](https://github.com/uprock/javascript) + - ![es](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Spain.png) **Spanish**: [paolocarrasco/javascript-style-guide](https://github.com/paolocarrasco/javascript-style-guide) + - ![th](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Thailand.png) **Thai**: [lvarayut/javascript-style-guide](https://github.com/lvarayut/javascript-style-guide) + - ![vn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Vietnam.png) **Vietnam**: [giangpii/javascript-style-guide](https://github.com/giangpii/javascript-style-guide) ## The JavaScript Style Guide Guide @@ -1629,7 +3066,7 @@ function foo() { (The MIT License) -Copyright (c) 2014 Airbnb +Copyright (c) 2014-2016 Airbnb Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -1652,4 +3089,8 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **[⬆ back to top](#table-of-contents)** +## Amendments + +We encourage you to fork this guide and change the rules to fit your team's style guide. Below, you may list some amendments to the style guide. This allows you to periodically update your style guide without having to deal with merge conflicts. + # }; diff --git a/linters/.eslintrc b/linters/.eslintrc new file mode 100644 index 0000000000..9e203a5473 --- /dev/null +++ b/linters/.eslintrc @@ -0,0 +1,5 @@ +// Use this file as a starting point for your project's .eslintrc. +// Copy this file, and add rule overrides as needed. +{ + "extends": "airbnb" +} diff --git a/linters/jshintrc b/linters/.jshintrc similarity index 84% rename from linters/jshintrc rename to linters/.jshintrc index d3b47148a8..a7a08a349e 100644 --- a/linters/jshintrc +++ b/linters/.jshintrc @@ -13,6 +13,9 @@ // Define globals exposed by Node.js. "node": true, + // Allow ES6. + "esversion": 6, + /* * ENFORCING OPTIONS * ================= @@ -25,23 +28,23 @@ // Prohibit use of == and != in favor of === and !==. "eqeqeq": true, - // Suppress warnings about == null comparisons. - "eqnull": true, - // Enforce tab width of 2 spaces. "indent": 2, // Prohibit use of a variable before it is defined. "latedef": true, + // Enforce line length to 100 characters + "maxlen": 100, + // Require capitalized names for constructor functions. "newcap": true, // Enforce use of single quotation marks for strings. "quotmark": "single", - // Prohibit trailing whitespace. - "trailing": true, + // Enforce placing 'use strict' at the top function scope + "strict": true, // Prohibit use of explicitly undeclared variables. "undef": true, @@ -49,9 +52,11 @@ // Warn when variables are defined but never used. "unused": true, - // Enforce line length to 80 characters - "maxlen": 80, + /* + * RELAXING OPTIONS + * ================= + */ - // Enforce placing 'use strict' at the top function scope - "strict": true + // Suppress warnings about == null comparisons. + "eqnull": true } diff --git a/linters/SublimeLinter/SublimeLinter.sublime-settings b/linters/SublimeLinter/SublimeLinter.sublime-settings index 12360f3f1c..259dbaff6a 100644 --- a/linters/SublimeLinter/SublimeLinter.sublime-settings +++ b/linters/SublimeLinter/SublimeLinter.sublime-settings @@ -63,7 +63,7 @@ // Warn when variables are defined but never used. "unused": true, - + // Enforce line length to 80 characters "maxlen": 80, diff --git a/package.json b/package.json new file mode 100644 index 0000000000..a977f26b3d --- /dev/null +++ b/package.json @@ -0,0 +1,35 @@ +{ + "name": "airbnb-style", + "version": "2.0.0", + "description": "A mostly reasonable approach to JavaScript.", + "scripts": { + "preinstall": "npm run install:config && npm run install:config:base", + "install:config": "cd packages/eslint-config-airbnb && npm prune && npm install", + "install:config:base": "cd packages/eslint-config-airbnb-base && npm prune && npm install", + "test": "npm run --silent test:config && npm run --silent test:config:base", + "test:config": "cd packages/eslint-config-airbnb; npm test", + "test:config:base": "cd packages/eslint-config-airbnb-base; npm test", + "travis": "npm run --silent travis:config && npm run --silent travis:config:base", + "travis:config": "cd packages/eslint-config-airbnb; npm run travis", + "travis:config:base": "cd packages/eslint-config-airbnb-base; npm run travis" + }, + "repository": { + "type": "git", + "url": "https://github.com/airbnb/javascript.git" + }, + "keywords": [ + "style guide", + "lint", + "airbnb", + "es6", + "es2015", + "react", + "jsx" + ], + "author": "Harrison Shoff (https://twitter.com/hshoff)", + "license": "MIT", + "bugs": { + "url": "https://github.com/airbnb/javascript/issues" + }, + "homepage": "https://github.com/airbnb/javascript" +} diff --git a/packages/eslint-config-airbnb-base/.babelrc b/packages/eslint-config-airbnb-base/.babelrc new file mode 100644 index 0000000000..e0aceaae1c --- /dev/null +++ b/packages/eslint-config-airbnb-base/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["airbnb"] +} diff --git a/packages/eslint-config-airbnb-base/.eslintrc b/packages/eslint-config-airbnb-base/.eslintrc new file mode 100644 index 0000000000..6c8556be3b --- /dev/null +++ b/packages/eslint-config-airbnb-base/.eslintrc @@ -0,0 +1,8 @@ +{ + "extends": "./index.js", + "rules": { + // disable requiring trailing commas because it might be nice to revert to + // being JSON at some point, and I don't want to make big changes now. + "comma-dangle": 0 + } +} diff --git a/packages/eslint-config-airbnb-base/CHANGELOG.md b/packages/eslint-config-airbnb-base/CHANGELOG.md new file mode 100644 index 0000000000..aa61e0f2be --- /dev/null +++ b/packages/eslint-config-airbnb-base/CHANGELOG.md @@ -0,0 +1,95 @@ +5.0.3 / 2016-08-21 +================== + - [fix] correct `import/extensions` list (#1013) + - [refactor] Changed ESLint rule configs to use 'off', 'warn', and 'error' instead of numbers for better readability (#946) + - [deps] update `eslint`, `eslint-plugin-react` + +5.0.2 / 2016-08-12 +================== + - [deps] update `eslint`, `eslint-find-rules`, `eslint-plugin-import` + - [tests] add `safe-publish-latest` to `prepublish` + +5.0.1 / 2016-07-29 +================== + - [patch] `no-unused-expressions`: flesh out options + - [deps] update `eslint` to `v3.2`, `eslint-plugin-import` to `v1.12` + - [tests] improve prepublish script + +5.0.0 / 2016-07-24 +================== + - [breaking] enable `import/newline-after-import` + - [breaking] enable overlooked rules: `linebreak-style`, `new-parens`, `no-continue`, `no-lonely-if`, `operator-assignment`, `space-unary-ops`, `dot-location`, `no-extra-boolean-cast`, `no-this-before-super`, `require-yield`, `no-path-concat`, `no-label-var`, `no-void`, `constructor-super`, `prefer-spread`, `no-new-require`, `no-undef-init`, `no-unexpected-multiline` + - [deps] update `eslint`, `eslint-find-rules`, `eslint-plugin-import`, `babel-tape-runner`; add `babel-preset-airbnb` + - [patch] flesh out defaults: `jsx-quotes` + - [docs] update the peer dep install command to dynamically look up the right version numbers when installing peer deps + - [tests] fix prepublish scripts + +4.0.2 / 2016-07-14 +================== + - [fix] repair accidental comma-dangle change + +4.0.1 / 2016-07-14 (unpublished) +================== + - [fix] Prevent trailing commas in the legacy config (#950) + - [deps] update `eslint-plugin-import` + +4.0.0 / 2016-07-02 +================== + - [breaking] [deps] update `eslint` to v3; drop support for < node 4 + - [breaking] enable `rest-spread-spacing` rule + - [breaking] enable `no-mixed-operators` rule + - [breaking] enable `import` rules: `no-named-as-default`, `no-named-as-default-member`, `no-extraneous-dependencies` + - [breaking] enable `object-property-newline` rule + - [breaking] enable `no-prototype-builtins` rule + - [breaking] enable `no-useless-rename` rule + - [breaking] enable `unicode-bom` rule + - [breaking] Enforce proper generator star spacing (#887) + - [breaking] Enable imports/imports-first rule (#882) + - [breaking] re-order rules; put import rules in separate file (#881) + - [patch] `newline-per-chained-call`: bump the limit to 4 + - [patch] `object-shorthand`: do not warn when the concise form would have a string literal as a name + - [patch] Loosen `prefer-const` to not warn when the variable is “read” before being assigned to + - [refactor] fix quoting of rule properties (#885) + - [refactor] `quotes`: Use object option form rather than deprecated string form. + - [deps] update `eslint`, `eslint-plugin-import`, `eslint-find-rules`, `tape` + - [tests] Only run `eslint-find-rules` on prepublish, not in tests + +3.0.1 / 2016-05-08 +================== + - [patch] re-disable `no-extra-parens` (#869, #867) + +3.0.0 / 2016-05-07 +================== + - [breaking] enable `import/no-mutable-exports` + - [breaking] enable `no-class-assign` rule, to pair with `no-func-assign` + - [breaking] widen `no-extra-parens` to include everything, except `nestedBinaryExpressions` + - [breaking] Re-enabling `newline-per-chained-call` (#748) + - [minor] enable `import/no-amd` + - [patch] enable `import/no-duplicates` + - [deps] update `eslint`, `eslint-plugin-import`, `eslint-find-rules` + +2.0.0 / 2016-04-29 +================== + - [breaking] enable `no-unsafe-finally` rule + - [semver-minor] enable `no-useless-computed-key` rule + - [deps] update `eslint`, `eslint-plugin-import` + +1.0.4 / 2016-04-26 +================== + - [deps] update `eslint-find-rules`, `eslint-plugin-import` + +1.0.3 / 2016-04-21 +================== + - [patch: loosen rules] Allow empty class/object methods + +1.0.2 / 2016-04-20 +================== + - [patch: loosen rules] Allow `break` (#840) + +1.0.1 / 2016-04-19 +================== + - [patch: loosen rules] Allow `== null` (#542) + +1.0.0 / 2016-04-19 +================== + - Initial commmit; moved content over from `eslint-config-airbnb` package. diff --git a/packages/eslint-config-airbnb-base/README.md b/packages/eslint-config-airbnb-base/README.md new file mode 100644 index 0000000000..40691b43c8 --- /dev/null +++ b/packages/eslint-config-airbnb-base/README.md @@ -0,0 +1,59 @@ +# eslint-config-airbnb-base + +[![npm version](https://badge.fury.io/js/eslint-config-airbnb-base.svg)](http://badge.fury.io/js/eslint-config-airbnb-base) + +This package provides Airbnb's base JS .eslintrc as an extensible shared config. + +## Usage + +We export two ESLint configurations for your usage. + +### eslint-config-airbnb-base + +Our default export contains all of our ESLint rules, including ECMAScript 6+. It requires `eslint` and `eslint-plugin-import`. + +1. Ensure packages are installed with correct version numbers by running: + ```sh + ( + export PKG=eslint-config-airbnb-base; + npm info "$PKG" peerDependencies --json | command sed 's/[\{\},]//g ; s/: /@/g' | xargs npm install --save-dev "$PKG" + ) + ``` + + Which produces and runs a command like: + + ```sh + npm install --save-dev eslint-config-airbnb-base eslint@^3.0.1 eslint-plugin-import@^1.10.3 + ``` + +2. Add `"extends": "airbnb-base"` to your .eslintrc + +### eslint-config-airbnb-base/legacy + +Lints ES5 and below. Requires `eslint` and `eslint-plugin-import`. + +1. Ensure packages are installed with correct version numbers by running: + ```sh + ( + export PKG=eslint-config-airbnb-base; + npm info "$PKG" peerDependencies --json | command sed 's/[\{\},]//g ; s/: /@/g' | xargs npm install --save-dev "$PKG" + ) + ``` + + Which produces and runs a command like: + + ```sh + npm install --save-dev eslint-config-airbnb-base eslint@^3.0.1 eslint-plugin-import@^1.10.3 + ``` + +2. Add `"extends": "airbnb-base/legacy"` to your .eslintrc + +See [Airbnb's overarching ESLint config](https://npmjs.com/eslint-config-airbnb), [Airbnb's Javascript styleguide](https://github.com/airbnb/javascript), and the [ESlint config docs](http://eslint.org/docs/user-guide/configuring#extending-configuration-files) for more information. + +## Improving this config + +Consider adding test cases if you're making complicated rules changes, like anything involving regexes. Perhaps in a distant future, we could use literate programming to structure our README as test cases for our .eslintrc? + +You can run tests with `npm test`. + +You can make sure this module lints with itself using `npm run lint`. diff --git a/packages/eslint-config-airbnb-base/index.js b/packages/eslint-config-airbnb-base/index.js new file mode 100644 index 0000000000..c89431a0c5 --- /dev/null +++ b/packages/eslint-config-airbnb-base/index.js @@ -0,0 +1,18 @@ +module.exports = { + extends: [ + './rules/best-practices', + './rules/errors', + './rules/node', + './rules/style', + './rules/variables', + './rules/es6', + './rules/imports', + ].map(require.resolve), + parserOptions: { + ecmaVersion: 7, + sourceType: 'module', + }, + rules: { + strict: 'error', + } +}; diff --git a/packages/eslint-config-airbnb-base/legacy.js b/packages/eslint-config-airbnb-base/legacy.js new file mode 100644 index 0000000000..9acfb1cb4e --- /dev/null +++ b/packages/eslint-config-airbnb-base/legacy.js @@ -0,0 +1,21 @@ +module.exports = { + extends: [ + './rules/best-practices', + './rules/errors', + './rules/node', + './rules/style', + './rules/variables' + ].map(require.resolve), + env: { + browser: true, + node: true, + amd: false, + mocha: false, + jasmine: false + }, + ecmaFeatures: {}, + globals: {}, + rules: { + 'comma-dangle': ['error', 'never'] + } +}; diff --git a/packages/eslint-config-airbnb-base/package.json b/packages/eslint-config-airbnb-base/package.json new file mode 100644 index 0000000000..5a04cd263d --- /dev/null +++ b/packages/eslint-config-airbnb-base/package.json @@ -0,0 +1,64 @@ +{ + "name": "eslint-config-airbnb-base", + "version": "5.0.3", + "description": "Airbnb's base JS ESLint config, following our styleguide", + "main": "index.js", + "scripts": { + "lint": "eslint .", + "tests-only": "babel-tape-runner ./test/test-*.js", + "prepublish": "(in-install || eslint-find-rules --unused) && (not-in-publish || npm test) && safe-publish-latest", + "pretest": "npm run --silent lint", + "test": "npm run --silent tests-only", + "travis": "npm run --silent test" + }, + "repository": { + "type": "git", + "url": "https://github.com/airbnb/javascript" + }, + "keywords": [ + "eslint", + "eslintconfig", + "config", + "airbnb", + "javascript", + "styleguide" + ], + "author": "Jake Teton-Landis (https://twitter.com/@jitl)", + "contributors": [ + { + "name": "Jake Teton-Landis", + "url": "https://twitter.com/jitl" + }, + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes/" + }, + { + "name": "Harrison Shoff", + "url": "https://twitter.com/hshoff" + } + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/airbnb/javascript/issues" + }, + "homepage": "https://github.com/airbnb/javascript", + "devDependencies": { + "babel-preset-airbnb": "^2.0.0", + "babel-tape-runner": "^2.0.1", + "eslint": "^3.3.1", + "eslint-find-rules": "^1.13.0", + "eslint-plugin-import": "^1.13.0", + "in-publish": "^2.0.0", + "safe-publish-latest": "^1.0.1", + "tape": "^4.6.0" + }, + "peerDependencies": { + "eslint": "^3.3.1", + "eslint-plugin-import": "^1.13.0" + }, + "engines": { + "node": ">= 4" + } +} diff --git a/packages/eslint-config-airbnb-base/rules/best-practices.js b/packages/eslint-config-airbnb-base/rules/best-practices.js new file mode 100644 index 0000000000..26602745de --- /dev/null +++ b/packages/eslint-config-airbnb-base/rules/best-practices.js @@ -0,0 +1,240 @@ +module.exports = { + rules: { + // enforces getter/setter pairs in objects + 'accessor-pairs': 'off', + + // enforces return statements in callbacks of array's methods + // http://eslint.org/docs/rules/array-callback-return + 'array-callback-return': 'error', + + // treat var statements as if they were block scoped + 'block-scoped-var': 'error', + + // specify the maximum cyclomatic complexity allowed in a program + complexity: ['off', 11], + + // require return statements to either always or never specify values + 'consistent-return': 'error', + + // specify curly brace conventions for all control statements + curly: ['error', 'multi-line'], + + // require default case in switch statements + 'default-case': ['error', { commentPattern: '^no default$' }], + + // encourages use of dot notation whenever possible + 'dot-notation': ['error', { allowKeywords: true }], + + // enforces consistent newlines before or after dots + // http://eslint.org/docs/rules/dot-location + 'dot-location': ['error', 'property'], + + // require the use of === and !== + // http://eslint.org/docs/rules/eqeqeq + eqeqeq: ['error', 'allow-null'], + + // make sure for-in loops have an if statement + 'guard-for-in': 'error', + + // disallow the use of alert, confirm, and prompt + 'no-alert': 'warn', + + // disallow use of arguments.caller or arguments.callee + 'no-caller': 'error', + + // disallow lexical declarations in case/default clauses + // http://eslint.org/docs/rules/no-case-declarations.html + 'no-case-declarations': 'error', + + // disallow division operators explicitly at beginning of regular expression + // http://eslint.org/docs/rules/no-div-regex + 'no-div-regex': 'off', + + // disallow else after a return in an if + 'no-else-return': 'error', + + // disallow empty functions, except for standalone funcs/arrows + // http://eslint.org/docs/rules/no-empty-function + 'no-empty-function': ['error', { + allow: [ + 'arrowFunctions', + 'functions', + 'methods', + ] + }], + + // disallow empty destructuring patterns + // http://eslint.org/docs/rules/no-empty-pattern + 'no-empty-pattern': 'error', + + // disallow comparisons to null without a type-checking operator + 'no-eq-null': 'off', + + // disallow use of eval() + 'no-eval': 'error', + + // disallow adding to native types + 'no-extend-native': 'error', + + // disallow unnecessary function binding + 'no-extra-bind': 'error', + + // disallow Unnecessary Labels + // http://eslint.org/docs/rules/no-extra-label + 'no-extra-label': 'error', + + // disallow fallthrough of case statements + 'no-fallthrough': 'error', + + // disallow the use of leading or trailing decimal points in numeric literals + 'no-floating-decimal': 'error', + + // disallow reassignments of native objects or read-only globals + // http://eslint.org/docs/rules/no-global-assign + 'no-global-assign': ['error', { exceptions: [] }], + + // disallow implicit type conversions + // http://eslint.org/docs/rules/no-implicit-coercion + 'no-implicit-coercion': ['off', { + boolean: false, + number: true, + string: true, + allow: [], + }], + + // disallow var and named functions in global scope + // http://eslint.org/docs/rules/no-implicit-globals + 'no-implicit-globals': 'off', + + // disallow use of eval()-like methods + 'no-implied-eval': 'error', + + // disallow this keywords outside of classes or class-like objects + 'no-invalid-this': 'off', + + // disallow usage of __iterator__ property + 'no-iterator': 'error', + + // disallow use of labels for anything other then loops and switches + 'no-labels': ['error', { allowLoop: false, allowSwitch: false }], + + // disallow unnecessary nested blocks + 'no-lone-blocks': 'error', + + // disallow creation of functions within loops + 'no-loop-func': 'error', + + // disallow magic numbers + // http://eslint.org/docs/rules/no-magic-numbers + 'no-magic-numbers': ['off', { + ignore: [], + ignoreArrayIndexes: true, + enforceConst: true, + detectObjects: false, + }], + + // disallow use of multiple spaces + 'no-multi-spaces': 'error', + + // disallow use of multiline strings + 'no-multi-str': 'error', + + // disallow reassignments of native objects + // TODO: deprecated in favor of no-global-assign + 'no-native-reassign': 'off', + + // disallow use of new operator when not part of the assignment or comparison + 'no-new': 'error', + + // disallow use of new operator for Function object + 'no-new-func': 'error', + + // disallows creating new instances of String, Number, and Boolean + 'no-new-wrappers': 'error', + + // disallow use of (old style) octal literals + 'no-octal': 'error', + + // disallow use of octal escape sequences in string literals, such as + // var foo = 'Copyright \251'; + 'no-octal-escape': 'error', + + // disallow reassignment of function parameters + // disallow parameter object manipulation + // rule: http://eslint.org/docs/rules/no-param-reassign.html + 'no-param-reassign': ['error', { props: true }], + + // disallow usage of __proto__ property + 'no-proto': 'error', + + // disallow declaring the same variable more then once + 'no-redeclare': 'error', + + // disallow use of assignment in return statement + 'no-return-assign': 'error', + + // disallow use of `javascript:` urls. + 'no-script-url': 'error', + + // disallow self assignment + // http://eslint.org/docs/rules/no-self-assign + 'no-self-assign': 'error', + + // disallow comparisons where both sides are exactly the same + 'no-self-compare': 'error', + + // disallow use of comma operator + 'no-sequences': 'error', + + // restrict what can be thrown as an exception + 'no-throw-literal': 'error', + + // disallow unmodified conditions of loops + // http://eslint.org/docs/rules/no-unmodified-loop-condition + 'no-unmodified-loop-condition': 'off', + + // disallow usage of expressions in statement position + 'no-unused-expressions': ['error', { + allowShortCircuit: false, + allowTernary: false, + }], + + // disallow unused labels + // http://eslint.org/docs/rules/no-unused-labels + 'no-unused-labels': 'error', + + // disallow unnecessary .call() and .apply() + 'no-useless-call': 'off', + + // disallow useless string concatenation + // http://eslint.org/docs/rules/no-useless-concat + 'no-useless-concat': 'error', + + // disallow unnecessary string escaping + // http://eslint.org/docs/rules/no-useless-escape + 'no-useless-escape': 'error', + + // disallow use of void operator + // http://eslint.org/docs/rules/no-void + 'no-void': 'error', + + // disallow usage of configurable warning terms in comments: e.g. todo + 'no-warning-comments': ['off', { terms: ['todo', 'fixme', 'xxx'], location: 'start' }], + + // disallow use of the with statement + 'no-with': 'error', + + // require use of the second argument for parseInt() + radix: 'error', + + // requires to declare all vars on top of their containing scope + 'vars-on-top': 'error', + + // require immediate function invocation to be wrapped in parentheses + // http://eslint.org/docs/rules/wrap-iife.html + 'wrap-iife': ['error', 'outside'], + + // require or disallow Yoda conditions + yoda: 'error' + } +}; diff --git a/packages/eslint-config-airbnb-base/rules/errors.js b/packages/eslint-config-airbnb-base/rules/errors.js new file mode 100644 index 0000000000..6c932c8dfc --- /dev/null +++ b/packages/eslint-config-airbnb-base/rules/errors.js @@ -0,0 +1,113 @@ +module.exports = { + rules: { + // require trailing commas in multiline object literals + 'comma-dangle': ['error', 'always-multiline'], + + // disallow assignment in conditional expressions + 'no-cond-assign': ['error', 'always'], + + // disallow use of console + 'no-console': 'warn', + + // disallow use of constant expressions in conditions + 'no-constant-condition': 'warn', + + // disallow control characters in regular expressions + 'no-control-regex': 'error', + + // disallow use of debugger + 'no-debugger': 'error', + + // disallow duplicate arguments in functions + 'no-dupe-args': 'error', + + // disallow duplicate keys when creating object literals + 'no-dupe-keys': 'error', + + // disallow a duplicate case label. + 'no-duplicate-case': 'error', + + // disallow empty statements + 'no-empty': 'error', + + // disallow the use of empty character classes in regular expressions + 'no-empty-character-class': 'error', + + // disallow assigning to the exception in a catch block + 'no-ex-assign': 'error', + + // disallow double-negation boolean casts in a boolean context + // http://eslint.org/docs/rules/no-extra-boolean-cast + 'no-extra-boolean-cast': 'error', + + // disallow unnecessary parentheses + // http://eslint.org/docs/rules/no-extra-parens + 'no-extra-parens': ['off', 'all', { + conditionalAssign: true, + nestedBinaryExpressions: false, + returnAssign: false, + }], + + // disallow unnecessary semicolons + 'no-extra-semi': 'error', + + // disallow overwriting functions written as function declarations + 'no-func-assign': 'error', + + // disallow function or variable declarations in nested blocks + 'no-inner-declarations': 'error', + + // disallow invalid regular expression strings in the RegExp constructor + 'no-invalid-regexp': 'error', + + // disallow irregular whitespace outside of strings and comments + 'no-irregular-whitespace': 'error', + + // disallow negation of the left operand of an in expression + // TODO: deprecated in favor of no-unsafe-negation + 'no-negated-in-lhs': 'off', + + // disallow the use of object properties of the global object (Math and JSON) as functions + 'no-obj-calls': 'error', + + // disallow use of Object.prototypes builtins directly + // http://eslint.org/docs/rules/no-prototype-builtins + 'no-prototype-builtins': 'error', + + // disallow multiple spaces in a regular expression literal + 'no-regex-spaces': 'error', + + // disallow sparse arrays + 'no-sparse-arrays': 'error', + + // Disallow template literal placeholder syntax in regular strings + // http://eslint.org/docs/rules/no-template-curly-in-string + // TODO: enable, semver-major + 'no-template-curly-in-string': 'off', + + // Avoid code that looks like two expressions but is actually one + // http://eslint.org/docs/rules/no-unexpected-multiline + 'no-unexpected-multiline': 'error', + + // disallow unreachable statements after a return, throw, continue, or break statement + 'no-unreachable': 'error', + + // disallow return/throw/break/continue inside finally blocks + // http://eslint.org/docs/rules/no-unsafe-finally + 'no-unsafe-finally': 'error', + + // disallow negating the left operand of relational operators + // http://eslint.org/docs/rules/no-unsafe-negation + 'no-unsafe-negation': 'error', + + // disallow comparisons with the value NaN + 'use-isnan': 'error', + + // ensure JSDoc comments are valid + // http://eslint.org/docs/rules/valid-jsdoc + 'valid-jsdoc': 'off', + + // ensure that the results of typeof are compared against a valid string + 'valid-typeof': 'error' + } +}; diff --git a/packages/eslint-config-airbnb-base/rules/es6.js b/packages/eslint-config-airbnb-base/rules/es6.js new file mode 100644 index 0000000000..169e30be01 --- /dev/null +++ b/packages/eslint-config-airbnb-base/rules/es6.js @@ -0,0 +1,145 @@ +module.exports = { + env: { + es6: true + }, + parserOptions: { + ecmaVersion: 6, + sourceType: 'module', + ecmaFeatures: { + generators: false, + objectLiteralDuplicateProperties: false + } + }, + + rules: { + // enforces no braces where they can be omitted + // http://eslint.org/docs/rules/arrow-body-style + 'arrow-body-style': ['error', 'as-needed'], + + // require parens in arrow function arguments + 'arrow-parens': 'off', + + // require space before/after arrow function's arrow + // http://eslint.org/docs/rules/arrow-spacing + 'arrow-spacing': ['error', { before: true, after: true }], + + // verify super() callings in constructors + 'constructor-super': 'error', + + // enforce the spacing around the * in generator functions + // http://eslint.org/docs/rules/generator-star-spacing + 'generator-star-spacing': ['error', { before: false, after: true }], + + // disallow modifying variables of class declarations + // http://eslint.org/docs/rules/no-class-assign + 'no-class-assign': 'error', + + // disallow arrow functions where they could be confused with comparisons + // http://eslint.org/docs/rules/no-confusing-arrow + 'no-confusing-arrow': ['error', { + allowParens: true, + }], + + // disallow modifying variables that are declared using const + 'no-const-assign': 'error', + + // disallow duplicate class members + // http://eslint.org/docs/rules/no-dupe-class-members + 'no-dupe-class-members': 'error', + + // disallow importing from the same path more than once + // http://eslint.org/docs/rules/no-duplicate-imports + 'no-duplicate-imports': 'error', + + // disallow symbol constructor + // http://eslint.org/docs/rules/no-new-symbol + 'no-new-symbol': 'error', + + // disallow specific imports + // http://eslint.org/docs/rules/no-restricted-imports + 'no-restricted-imports': 'off', + + // disallow to use this/super before super() calling in constructors. + // http://eslint.org/docs/rules/no-this-before-super + 'no-this-before-super': 'error', + + // disallow useless computed property keys + // http://eslint.org/docs/rules/no-useless-computed-key + 'no-useless-computed-key': 'error', + + // disallow unnecessary constructor + // http://eslint.org/docs/rules/no-useless-constructor + 'no-useless-constructor': 'error', + + // disallow renaming import, export, and destructured assignments to the same name + // http://eslint.org/docs/rules/no-useless-rename + 'no-useless-rename': ['error', { + ignoreDestructuring: false, + ignoreImport: false, + ignoreExport: false, + }], + + // require let or const instead of var + 'no-var': 'error', + + // require method and property shorthand syntax for object literals + // http://eslint.org/docs/rules/object-shorthand + 'object-shorthand': ['error', 'always', { + ignoreConstructors: false, + avoidQuotes: true, + }], + + // suggest using arrow functions as callbacks + 'prefer-arrow-callback': ['error', { + allowNamedFunctions: false, + allowUnboundThis: true, + }], + + // suggest using of const declaration for variables that are never modified after declared + 'prefer-const': ['error', { + destructuring: 'any', + ignoreReadBeforeAssign: true, + }], + + // suggest using Reflect methods where applicable + // http://eslint.org/docs/rules/prefer-reflect + // TODO: enable + 'prefer-reflect': 'off', + + // use rest parameters instead of arguments + // http://eslint.org/docs/rules/prefer-rest-params + 'prefer-rest-params': 'error', + + // suggest using the spread operator instead of .apply() + // http://eslint.org/docs/rules/prefer-spread + 'prefer-spread': 'error', + + // suggest using template literals instead of string concatenation + // http://eslint.org/docs/rules/prefer-template + 'prefer-template': 'error', + + // disallow generator functions that do not have yield + // http://eslint.org/docs/rules/require-yield + 'require-yield': 'error', + + // enforce spacing between object rest-spread + // http://eslint.org/docs/rules/rest-spread-spacing + 'rest-spread-spacing': ['error', 'never'], + + // import sorting + // http://eslint.org/docs/rules/sort-imports + 'sort-imports': ['off', { + ignoreCase: false, + ignoreMemberSort: false, + memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'], + }], + + // enforce usage of spacing in template strings + // http://eslint.org/docs/rules/template-curly-spacing + 'template-curly-spacing': 'error', + + // enforce spacing around the * in yield* expressions + // http://eslint.org/docs/rules/yield-star-spacing + 'yield-star-spacing': ['error', 'after'] + } +}; diff --git a/packages/eslint-config-airbnb-base/rules/imports.js b/packages/eslint-config-airbnb-base/rules/imports.js new file mode 100644 index 0000000000..09f2397c70 --- /dev/null +++ b/packages/eslint-config-airbnb-base/rules/imports.js @@ -0,0 +1,133 @@ +module.exports = { + env: { + es6: true + }, + parserOptions: { + ecmaVersion: 6, + sourceType: 'module' + }, + plugins: [ + 'import' + ], + + settings: { + 'import/resolver': { + node: { + extensions: ['.js', '.json'] + } + }, + 'import/extensions': [ + '.js', + '.jsx', + ], + 'import/core-modules': [ + ], + 'import/ignore': [ + 'node_modules', + '\\.(coffee|scss|css|less|hbs|svg|json)$', + ], + }, + + rules: { + // Static analysis: + + // ensure imports point to files/modules that can be resolved + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md + 'import/no-unresolved': ['error', { commonjs: true }], + + // ensure named imports coupled with named exports + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/named.md#when-not-to-use-it + 'import/named': 'off', + + // ensure default import coupled with default export + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/default.md#when-not-to-use-it + 'import/default': 'off', + + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/namespace.md + 'import/namespace': 'off', + + // Helpful warnings: + + // disallow invalid exports, e.g. multiple defaults + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/export.md + 'import/export': 'error', + + // do not allow a default import name to match a named export + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default.md + 'import/no-named-as-default': 'error', + + // warn on accessing default export property names that are also named exports + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default-member.md + 'import/no-named-as-default-member': 'error', + + // disallow use of jsdoc-marked-deprecated imports + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md + 'import/no-deprecated': 'off', + + // Forbid the use of extraneous packages + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md + 'import/no-extraneous-dependencies': ['error', { + devDependencies: false, + optionalDependencies: false, + }], + + // Forbid mutable exports + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md + 'import/no-mutable-exports': 'error', + + // Module systems: + + // disallow require() + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-commonjs.md + 'import/no-commonjs': 'off', + + // disallow AMD require/define + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-amd.md + 'import/no-amd': 'error', + + // No Node.js builtin modules + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-nodejs-modules.md + // TODO: enable? + 'import/no-nodejs-modules': 'off', + + // Style guide: + + // disallow non-import statements appearing before import statements + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/imports-first.md + 'import/imports-first': ['error', 'absolute-first'], + + // disallow duplicate imports + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md + 'import/no-duplicates': 'error', + + // disallow namespace imports + // TODO: enable? + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-namespace.md + 'import/no-namespace': 'off', + + // Ensure consistent use of file extension within the import path + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/extensions.md + // TODO: enable when https://github.com/benmosher/eslint-plugin-import/issues/390 is resolved + 'import/extensions': ['off', 'never'], + + // Enforce a convention in module import order + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/order.md + // TODO: enable? + 'import/order': ['off', { + groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'], + 'newlines-between': 'never', + }], + + // Require a newline after the last import/require in a group + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md + 'import/newline-after-import': 'error', + + // Require modules with a single export to use a default export + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md + 'import/prefer-default-export': 'error', + + // Restrict which files can be imported in a given folder + // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-restricted-paths.md + 'import/no-restricted-paths': 'off', + }, +}; diff --git a/packages/eslint-config-airbnb-base/rules/node.js b/packages/eslint-config-airbnb-base/rules/node.js new file mode 100644 index 0000000000..e4a71a6a5a --- /dev/null +++ b/packages/eslint-config-airbnb-base/rules/node.js @@ -0,0 +1,39 @@ +module.exports = { + env: { + node: true + }, + + rules: { + // enforce return after a callback + 'callback-return': 'off', + + // require all requires be top-level + // http://eslint.org/docs/rules/global-require + 'global-require': 'error', + + // enforces error handling in callbacks (node environment) + 'handle-callback-err': 'off', + + // disallow mixing regular variable and require declarations + 'no-mixed-requires': ['off', false], + + // disallow use of new operator with the require function + 'no-new-require': 'error', + + // disallow string concatenation with __dirname and __filename + // http://eslint.org/docs/rules/no-path-concat + 'no-path-concat': 'error', + + // disallow use of process.env + 'no-process-env': 'off', + + // disallow process.exit() + 'no-process-exit': 'off', + + // restrict usage of specified node modules + 'no-restricted-modules': 'off', + + // disallow use of synchronous methods (off by default) + 'no-sync': 'off', + } +}; diff --git a/packages/eslint-config-airbnb-base/rules/strict.js b/packages/eslint-config-airbnb-base/rules/strict.js new file mode 100644 index 0000000000..67cfd5e8a3 --- /dev/null +++ b/packages/eslint-config-airbnb-base/rules/strict.js @@ -0,0 +1,6 @@ +module.exports = { + rules: { + // babel inserts `'use strict';` for us + strict: ['error', 'never'] + } +}; diff --git a/packages/eslint-config-airbnb-base/rules/style.js b/packages/eslint-config-airbnb-base/rules/style.js new file mode 100644 index 0000000000..c80beaee87 --- /dev/null +++ b/packages/eslint-config-airbnb-base/rules/style.js @@ -0,0 +1,312 @@ +module.exports = { + rules: { + // enforce spacing inside array brackets + 'array-bracket-spacing': ['error', 'never'], + + // enforce spacing inside single-line blocks + // http://eslint.org/docs/rules/block-spacing + 'block-spacing': ['error', 'always'], + + // enforce one true brace style + 'brace-style': ['error', '1tbs', { allowSingleLine: true }], + + // require camel case names + camelcase: ['error', { properties: 'never' }], + + // enforce spacing before and after comma + 'comma-spacing': ['error', { before: false, after: true }], + + // enforce one true comma style + 'comma-style': ['error', 'last'], + + // disallow padding inside computed properties + 'computed-property-spacing': ['error', 'never'], + + // enforces consistent naming when capturing the current execution context + 'consistent-this': 'off', + + // enforce newline at the end of file, with no multiple empty lines + 'eol-last': 'error', + + // enforce spacing between functions and their invocations + // http://eslint.org/docs/rules/func-call-spacing + // TODO: enable, semver-minor + 'func-call-spacing': ['off', 'never'], + + // require function expressions to have a name + 'func-names': 'warn', + + // enforces use of function declarations or expressions + 'func-style': 'off', + + // Blacklist certain identifiers to prevent them being used + // http://eslint.org/docs/rules/id-blacklist + 'id-blacklist': 'off', + + // this option enforces minimum and maximum identifier lengths + // (variable names, property names etc.) + 'id-length': 'off', + + // require identifiers to match the provided regular expression + 'id-match': 'off', + + // this option sets a specific tab width for your code + // http://eslint.org/docs/rules/indent + indent: ['error', 2, { SwitchCase: 1, VariableDeclarator: 1, outerIIFEBody: 1 }], + + // specify whether double or single quotes should be used in JSX attributes + // http://eslint.org/docs/rules/jsx-quotes + 'jsx-quotes': ['off', 'prefer-double'], + + // enforces spacing between keys and values in object literal properties + 'key-spacing': ['error', { beforeColon: false, afterColon: true }], + + // require a space before & after certain keywords + 'keyword-spacing': ['error', { + before: true, + after: true, + overrides: { + return: { after: true }, + throw: { after: true }, + case: { after: true } + } + }], + + // disallow mixed 'LF' and 'CRLF' as linebreaks + // http://eslint.org/docs/rules/linebreak-style + 'linebreak-style': ['error', 'unix'], + + // enforces empty lines around comments + 'lines-around-comment': 'off', + + // specify the maximum depth that blocks can be nested + 'max-depth': ['off', 4], + + // specify the maximum length of a line in your program + // http://eslint.org/docs/rules/max-len + 'max-len': ['error', 100, 2, { + ignoreUrls: true, + ignoreComments: false + }], + + // specify the max number of lines in a file + // http://eslint.org/docs/rules/max-lines + 'max-lines': ['off', { + max: 300, + skipBlankLines: true, + skipComments: true + }], + + // specify the maximum depth callbacks can be nested + 'max-nested-callbacks': 'off', + + // limits the number of parameters that can be used in the function declaration. + 'max-params': ['off', 3], + + // specify the maximum number of statement allowed in a function + 'max-statements': ['off', 10], + + // restrict the number of statements per line + // http://eslint.org/docs/rules/max-statements-per-line + 'max-statements-per-line': ['off', { max: 1 }], + + // require multiline ternary + // http://eslint.org/docs/rules/multiline-ternary + 'multiline-ternary': 'off', + + // require a capital letter for constructors + 'new-cap': ['error', { newIsCap: true }], + + // disallow the omission of parentheses when invoking a constructor with no arguments + // http://eslint.org/docs/rules/new-parens + 'new-parens': 'error', + + // allow/disallow an empty newline after var statement + 'newline-after-var': 'off', + + // http://eslint.org/docs/rules/newline-before-return + 'newline-before-return': 'off', + + // enforces new line after each method call in the chain to make it + // more readable and easy to maintain + // http://eslint.org/docs/rules/newline-per-chained-call + 'newline-per-chained-call': ['error', { ignoreChainWithDepth: 4 }], + + // disallow use of the Array constructor + 'no-array-constructor': 'error', + + // disallow use of bitwise operators + // http://eslint.org/docs/rules/no-bitwise + // TODO: enable + 'no-bitwise': 'off', + + // disallow use of the continue statement + // http://eslint.org/docs/rules/no-continue + 'no-continue': 'error', + + // disallow comments inline after code + 'no-inline-comments': 'off', + + // disallow if as the only statement in an else block + // http://eslint.org/docs/rules/no-lonely-if + 'no-lonely-if': 'error', + + // disallow un-paren'd mixes of different operators + // http://eslint.org/docs/rules/no-mixed-operators + 'no-mixed-operators': ['error', { + groups: [ + ['+', '-', '*', '/', '%', '**'], + ['&', '|', '^', '~', '<<', '>>', '>>>'], + ['==', '!=', '===', '!==', '>', '>=', '<', '<='], + ['&&', '||'], + ['in', 'instanceof'] + ], + allowSamePrecedence: false + }], + + // disallow mixed spaces and tabs for indentation + 'no-mixed-spaces-and-tabs': 'error', + + // disallow multiple empty lines and only one newline at the end + 'no-multiple-empty-lines': ['error', { max: 2, maxEOF: 1 }], + + // disallow negated conditions + // http://eslint.org/docs/rules/no-negated-condition + 'no-negated-condition': 'off', + + // disallow nested ternary expressions + 'no-nested-ternary': 'error', + + // disallow use of the Object constructor + 'no-new-object': 'error', + + // disallow use of unary operators, ++ and -- + 'no-plusplus': 'off', + + // disallow certain syntax forms + // http://eslint.org/docs/rules/no-restricted-syntax + 'no-restricted-syntax': [ + 'error', + 'ForInStatement', + 'LabeledStatement', + 'WithStatement', + ], + + // disallow space between function identifier and application + 'no-spaced-func': 'error', + + // disallow tab characters entirely + // TODO: enable + 'no-tabs': 'off', + + // disallow the use of ternary operators + 'no-ternary': 'off', + + // disallow trailing whitespace at the end of lines + 'no-trailing-spaces': 'error', + + // disallow dangling underscores in identifiers + 'no-underscore-dangle': ['error', { allowAfterThis: false }], + + // disallow the use of Boolean literals in conditional expressions + // also, prefer `a || b` over `a ? a : b` + // http://eslint.org/docs/rules/no-unneeded-ternary + 'no-unneeded-ternary': ['error', { defaultAssignment: false }], + + // disallow whitespace before properties + // http://eslint.org/docs/rules/no-whitespace-before-property + 'no-whitespace-before-property': 'error', + + // require padding inside curly braces + 'object-curly-spacing': ['error', 'always'], + + // enforce line breaks between braces + // http://eslint.org/docs/rules/object-curly-newline + // TODO: enable once https://github.com/eslint/eslint/issues/6488 is resolved + 'object-curly-newline': ['off', { + ObjectExpression: { minProperties: 0, multiline: true }, + ObjectPattern: { minProperties: 0, multiline: true } + }], + + // enforce "same line" or "multiple line" on object properties. + // http://eslint.org/docs/rules/object-property-newline + 'object-property-newline': ['error', { + allowMultiplePropertiesPerLine: true, + }], + + // allow just one var statement per function + 'one-var': ['error', 'never'], + + // require a newline around variable declaration + // http://eslint.org/docs/rules/one-var-declaration-per-line + 'one-var-declaration-per-line': ['error', 'always'], + + // require assignment operator shorthand where possible or prohibit it entirely + // http://eslint.org/docs/rules/operator-assignment + 'operator-assignment': ['error', 'always'], + + // enforce operators to be placed before or after line breaks + 'operator-linebreak': 'off', + + // enforce padding within blocks + 'padded-blocks': ['error', 'never'], + + // require quotes around object literal property names + // http://eslint.org/docs/rules/quote-props.html + 'quote-props': ['error', 'as-needed', { keywords: false, unnecessary: true, numbers: false }], + + // specify whether double or single quotes should be used + quotes: ['error', 'single', { avoidEscape: true }], + + // do not require jsdoc + // http://eslint.org/docs/rules/require-jsdoc + 'require-jsdoc': 'off', + + // require or disallow use of semicolons instead of ASI + semi: ['error', 'always'], + + // enforce spacing before and after semicolons + 'semi-spacing': ['error', { before: false, after: true }], + + // requires object keys to be sorted + 'sort-keys': ['off', 'asc', { caseSensitive: false, natural: true }], + + // sort variables within the same declaration block + 'sort-vars': 'off', + + // require or disallow space before blocks + 'space-before-blocks': 'error', + + // require or disallow space before function opening parenthesis + // http://eslint.org/docs/rules/space-before-function-paren + 'space-before-function-paren': ['error', { anonymous: 'always', named: 'never' }], + + // require or disallow spaces inside parentheses + 'space-in-parens': ['error', 'never'], + + // require spaces around operators + 'space-infix-ops': 'error', + + // Require or disallow spaces before/after unary operators + // http://eslint.org/docs/rules/space-unary-ops + 'space-unary-ops': ['error', { + words: true, + nonwords: false, + overrides: { + }, + }], + + // require or disallow a space immediately following the // or /* in a comment + 'spaced-comment': ['error', 'always', { + exceptions: ['-', '+'], + markers: ['=', '!'] // space here to support sprockets directives + }], + + // require or disallow the Unicode Byte Order Mark + // http://eslint.org/docs/rules/unicode-bom + 'unicode-bom': ['error', 'never'], + + // require regex literals to be wrapped in parentheses + 'wrap-regex': 'off' + } +}; diff --git a/packages/eslint-config-airbnb-base/rules/variables.js b/packages/eslint-config-airbnb-base/rules/variables.js new file mode 100644 index 0000000000..312ee76813 --- /dev/null +++ b/packages/eslint-config-airbnb-base/rules/variables.js @@ -0,0 +1,41 @@ +module.exports = { + rules: { + // enforce or disallow variable initializations at definition + 'init-declarations': 'off', + + // disallow the catch clause parameter name being the same as a variable in the outer scope + 'no-catch-shadow': 'off', + + // disallow deletion of variables + 'no-delete-var': 'error', + + // disallow labels that share a name with a variable + // http://eslint.org/docs/rules/no-label-var + 'no-label-var': 'error', + + // disallow specific globals + 'no-restricted-globals': 'off', + + // disallow declaration of variables already declared in the outer scope + 'no-shadow': 'error', + + // disallow shadowing of names such as arguments + 'no-shadow-restricted-names': 'error', + + // disallow use of undeclared variables unless mentioned in a /*global */ block + 'no-undef': 'error', + + // disallow use of undefined when initializing variables + 'no-undef-init': 'error', + + // disallow use of undefined variable + // TODO: enable? + 'no-undefined': 'off', + + // disallow declaration of variables that are not used in the code + 'no-unused-vars': ['error', { vars: 'local', args: 'after-used' }], + + // disallow use of variables before they are defined + 'no-use-before-define': 'error' + } +}; diff --git a/packages/eslint-config-airbnb-base/test/.eslintrc b/packages/eslint-config-airbnb-base/test/.eslintrc new file mode 100644 index 0000000000..7e22f26a09 --- /dev/null +++ b/packages/eslint-config-airbnb-base/test/.eslintrc @@ -0,0 +1,12 @@ +{ + "rules": { + // disabled because I find it tedious to write tests while following this + // rule + "no-shadow": 0, + // tests uses `t` for tape + "id-length": [2, {"min": 2, "properties": "never", "exceptions": ["t"]}], + "import/no-extraneous-dependencies": [2, { + "devDependencies": true + }], + } +} diff --git a/packages/eslint-config-airbnb-base/test/test-base.js b/packages/eslint-config-airbnb-base/test/test-base.js new file mode 100644 index 0000000000..8e7dc8cd2d --- /dev/null +++ b/packages/eslint-config-airbnb-base/test/test-base.js @@ -0,0 +1,29 @@ +import fs from 'fs'; +import path from 'path'; +import test from 'tape'; + +import index from '../'; + +const files = { index }; + +fs.readdirSync(path.join(__dirname, '../rules')).forEach(name => { + files[name] = require(`../rules/${name}`); // eslint-disable-line global-require +}); + +Object.keys(files).forEach(name => { + const config = files[name]; + + test(`${name}: does not reference react`, t => { + t.plan(2); + + // scan plugins for react and fail if it is found + const hasReactPlugin = Object.prototype.hasOwnProperty.call(config, 'plugins') && + config.plugins.indexOf('react') !== -1; + t.notOk(hasReactPlugin, 'there is no react plugin'); + + // scan rules for react/ and fail if any exist + const reactRuleIds = Object.keys(config.rules) + .filter(ruleId => ruleId.indexOf('react/') === 0); + t.deepEquals(reactRuleIds, [], 'there are no react/ rules'); + }); +}); diff --git a/packages/eslint-config-airbnb/.babelrc b/packages/eslint-config-airbnb/.babelrc new file mode 100644 index 0000000000..e0aceaae1c --- /dev/null +++ b/packages/eslint-config-airbnb/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["airbnb"] +} diff --git a/packages/eslint-config-airbnb/.eslintrc b/packages/eslint-config-airbnb/.eslintrc new file mode 100644 index 0000000000..6c8556be3b --- /dev/null +++ b/packages/eslint-config-airbnb/.eslintrc @@ -0,0 +1,8 @@ +{ + "extends": "./index.js", + "rules": { + // disable requiring trailing commas because it might be nice to revert to + // being JSON at some point, and I don't want to make big changes now. + "comma-dangle": 0 + } +} diff --git a/packages/eslint-config-airbnb/CHANGELOG.md b/packages/eslint-config-airbnb/CHANGELOG.md new file mode 100644 index 0000000000..bb88fb3659 --- /dev/null +++ b/packages/eslint-config-airbnb/CHANGELOG.md @@ -0,0 +1,266 @@ +10.0.1 / 2016-08-12 +================== +- [deps] update `eslint`, `eslint-find-rules`, `eslint-plugin-jsx-a11y`, `eslint-plugin-import`, `eslint-config-airbnb-base` + +10.0.0 / 2016-08-01 +================== +- [breaking] enable jsx-a11y rules: + - `jsx-a11y/heading-has-content` + - `jsx-a11y/html-has-lang` + - `jsx-a11y/lang` + - `jsx-a11y/no-marquee` + - `jsx-a11y/scope` + - `jsx-a11y/href-no-hash` + - `jsx-a11y/label-has-for` +- [breaking] enable aria rules: + - `jsx-a11y/aria-props` + - `jsx-a11y/aria-proptypes` + - `jsx-a11y/aria-unsupported-elements` + - `jsx-a11y/role-has-required-aria-props` + - `jsx-a11y/role-supports-aria-props` +- [breaking] enable react rules: + - `react/jsx-filename-extension` + - `react/jsx-no-comment-textnodes` + - `react/jsx-no-target-blank` + - `react/require-extension` + - `react/no-render-return-value` + - `react/no-find-dom-node` + - `react/no-deprecated` +- [deps] [breaking] update `eslint` to v3, `eslint-config-airbnb-base` to v5, `eslint-find-rules`, `eslint-plugin-import`, `eslint-plugin-jsx-a11y` to v2, `eslint-plugin-react` to v6, `tape`. drop node < 4 support. +- [deps] update `eslint-config-airbnb-base`, `eslint-plugin-react`, `eslint-plugin-import`, `eslint-plugin-jsx-a11y`, `babel-tape-runner`, add `babel-preset-airbnb`. ensure react is `>=` 0.13.0 +- [patch] loosen `jsx-pascal-case` rule to allow all caps component names +- [tests] stop testing < node 4 +- [tests] use `in-publish` because coffeescript screwed up the prepublish script for everyone +- [tests] Only run `eslint-find-rules` on prepublish, not in tests +- [tests] Even though the base config may not be up to date in the main package, let’s `npm link` the base package into the main one for the sake of travis-ci tests +- [docs] update the peer dep install command to dynamically look up the right version numbers when installing peer deps +- add `safe-publish-latest` to `prepublish` + +9.0.1 / 2016-05-08 +================== +- [patch] update `eslint-config-airbnb-base` to v3.0.1 + +9.0.0 / 2016-05-07 +================== +- [breaking] update `eslint-config-airbnb-base` to v3 +- [deps] update `eslint-find-rules`, `eslint-plugin-import`, `eslint-plugin-jsx-a11y` + +8.0.0 / 2016-04-21 +================== +- [breaking] Migrate non-React rules to a separate linter config (`eslint-config-airbnb-base`) +- [breaking] disallow empty methods +- [breaking] disallow empty restructuring patterns +- [breaking] enable `no-restricted-syntax` rule +- [breaking] enable `global-require` rule +- [breaking] [react] enable `react/jsx-curly-spacing` rule ([#693](https://github.com/airbnb/javascript/issues/693)) +- [semver-minor] [react] Add `react/jsx-first-prop-new-line` rule +- [semver-minor] [react] enable `jsx-equals-spacing` rule +- [semver-minor] [react] enable `jsx-indent` rule +- [semver-minor] enforce spacing inside single-line blocks +- [semver-minor] enforce `no-underscore-dangle` +- [semver-minor] Enable import/no-unresolved and import/export rules ([#825](https://github.com/airbnb/javascript/issues/825)) +- [semver-patch] Enable `no-useless-concat` rule which `prefer-template` already covers +- [semver-patch] Allow `== null` ([#542](https://github.com/airbnb/javascript/issues/542)) +- [dev deps / peer deps] update `eslint`, `eslint-plugin-react`, `eslint-plugin-import` +- [dev deps / peer deps] update `eslint-plugin-jsx-a11y` and rename rules ([#838](https://github.com/airbnb/javascript/issues/838)) +- [refactor] [react] separate a11y rules to their own file +- [refactor] Add missing disabled rules. +- [tests] Add `eslint-find-rules` to prevent missing rules + +7.0.0 / 2016-04-11 +================== +- [react] [breaking] Add accessibility rules to the React style guide + `eslint-plugin-a11y` +- [breaking] enable `react/require-render-return` +- [breaking] Add `no-dupe-class-members` rule + section ([#785](https://github.com/airbnb/javascript/issues/785)) +- [breaking] error on debugger statements +- [breaking] add `no-useless-escape` rule +- [breaking] add `no-duplicate-imports` rule +- [semver-minor] enable `jsx-pascal-case` rule +- [deps] update `eslint`, `react` +- [dev deps] update `eslint`, `eslint-plugin-react` + +6.2.0 / 2016-03-22 +================== +- [new] Allow arrow functions in JSX props +- [fix] re-enable `no-confusing-arrow` rule, with `allowParens` option enabled ([#752](https://github.com/airbnb/javascript/issues/752), [#791](https://github.com/airbnb/javascript/issues/791)) +- [dev deps] update `tape`, `eslint`, `eslint-plugin-react` +- [peer deps] update `eslint`, `eslint-plugin-react` + +6.1.0 / 2016-02-22 +================== +- [new] enable [`react/prefer-stateless-function`][react/prefer-stateless-function] +- [dev deps] update `react-plugin-eslint`, `eslint`, `tape` + +6.0.2 / 2016-02-22 +================== +- [fix] disable [`no-confusing-arrow`][no-confusing-arrow] due to an `eslint` bug ([#752](https://github.com/airbnb/javascript/issues/752)) + +6.0.1 / 2016-02-21 +================== +- [fix] disable [`newline-per-chained-call`][newline-per-chained-call] due to an `eslint` bug ([#748](https://github.com/airbnb/javascript/issues/748)) + +6.0.0 / 2016-02-21 +================== +- [breaking] enable [`array-callback-return`][array-callback-return] +- [breaking] enable [`no-confusing-arrow`][no-confusing-arrow] +- [breaking] enable [`no-new-symbol`][no-new-symbol] +- [breaking] enable [`no-restricted-imports`][no-restricted-imports] +- [breaking] enable [`no-useless-constructor`][no-useless-constructor] +- [breaking] enable [`prefer-rest-params`][prefer-rest-params] +- [breaking] enable [`template-curly-spacing`][template-curly-spacing] +- [breaking] enable [`newline-per-chained-call`][newline-per-chained-call] +- [breaking] enable [`one-var-declaration-per-line`][one-var-declaration-per-line] +- [breaking] enable [`no-self-assign`][no-self-assign] +- [breaking] enable [`no-whitespace-before-property`][no-whitespace-before-property] +- [breaking] [react] enable [`react/jsx-space-before-closing`][react/jsx-space-before-closing] +- [breaking] [react] enable `static-methods` at top of [`react/sort-comp`][react/sort-comp] +- [breaking] [react] don't `ignoreTranspilerName` for [`react/display-name`][react/display-name] +- [peer+dev deps] update `eslint`, `eslint-plugin-react` ([#730](https://github.com/airbnb/javascript/issues/730)) + +5.0.1 / 2016-02-13 +================== +- [fix] `eslint` peerDep should not include breaking changes + +5.0.0 / 2016-02-03 +================== +- [breaking] disallow unneeded ternary expressions +- [breaking] Avoid lexical declarations in case/default clauses +- [dev deps] update `babel-tape-runner`, `eslint-plugin-react`, `react`, `tape` + +4.0.0 / 2016-01-22 +================== +- [breaking] require outer IIFE wrapping; flesh out guide section +- [minor] Add missing [`arrow-body-style`][arrow-body-style], [`prefer-template`][prefer-template] rules ([#678](https://github.com/airbnb/javascript/issues/678)) +- [minor] Add [`prefer-arrow-callback`][prefer-arrow-callback] to ES6 rules (to match the guide) ([#677](https://github.com/airbnb/javascript/issues/677)) +- [Tests] run `npm run lint` as part of tests; fix errors +- [Tests] use `parallelshell` to parallelize npm run-scripts + +3.1.0 / 2016-01-07 +================== +- [minor] Allow multiple stateless components in a single file + +3.0.2 / 2016-01-06 +================== +- [fix] Ignore URLs in [`max-len`][max-len] ([#664](https://github.com/airbnb/javascript/issues/664)) + +3.0.1 / 2016-01-06 +================== +- [fix] because we use babel, keywords should not be quoted + +3.0.0 / 2016-01-04 +================== +- [breaking] enable [`quote-props`][quote-props] rule ([#632](https://github.com/airbnb/javascript/issues/632)) +- [breaking] Define a max line length of 100 characters ([#639](https://github.com/airbnb/javascript/issues/639)) +- [breaking] [react] Minor cleanup for the React styleguide, add [`react/jsx-no-bind`][react/jsx-no-bind] ([#619](https://github.com/airbnb/javascript/issues/619)) +- [breaking] update best-practices config to prevent parameter object manipulation ([#627](https://github.com/airbnb/javascript/issues/627)) +- [minor] Enable [`react/no-is-mounted`][react/no-is-mounted] rule (#635, #633) +- [minor] Sort [`react/prefer-es6-class`][react/prefer-es6-class] alphabetically ([#634](https://github.com/airbnb/javascript/issues/634)) +- [minor] enable [`react/prefer-es6-class`][react/prefer-es6-class] rule +- Permit strict mode in "legacy" config +- [react] add missing rules from `eslint-plugin-react` (enforcing where necessary) ([#581](https://github.com/airbnb/javascript/issues/581)) +- [dev deps] update `eslint-plugin-react` + +2.1.1 / 2015-12-15 +================== +- [fix] Remove deprecated [`react/jsx-quotes`][react/jsx-quotes] ([#622](https://github.com/airbnb/javascript/issues/622)) + +2.1.0 / 2015-12-15 +================== +- [fix] use `require.resolve` to allow nested `extend`s ([#582](https://github.com/airbnb/javascript/issues/582)) +- [new] enable [`object-shorthand`][object-shorthand] rule ([#621](https://github.com/airbnb/javascript/issues/621)) +- [new] enable [`arrow-spacing`][arrow-spacing] rule ([#517](https://github.com/airbnb/javascript/issues/517)) +- [docs] flesh out react rule defaults ([#618](https://github.com/airbnb/javascript/issues/618)) + +2.0.0 / 2015-12-03 +================== +- [breaking] [`space-before-function-paren`][space-before-function-paren]: require function spacing: `function (` ([#605](https://github.com/airbnb/javascript/issues/605)) +- [breaking] [`indent`][indent]: Fix switch statement indentation rule ([#606](https://github.com/airbnb/javascript/issues/606)) +- [breaking] [`array-bracket-spacing`][array-bracket-spacing], [`computed-property-spacing`][computed-property-spacing]: disallow spacing inside brackets ([#594](https://github.com/airbnb/javascript/issues/594)) +- [breaking] [`object-curly-spacing`][object-curly-spacing]: require padding inside curly braces ([#594](https://github.com/airbnb/javascript/issues/594)) +- [breaking] [`space-in-parens`][space-in-parens]: disallow spaces in parens ([#594](https://github.com/airbnb/javascript/issues/594)) + +1.0.2 / 2015-11-25 +================== +- [breaking] [`no-multiple-empty-lines`][no-multiple-empty-lines]: only allow 1 blank line at EOF ([#578](https://github.com/airbnb/javascript/issues/578)) +- [new] `restParams`: enable rest params ([#592](https://github.com/airbnb/javascript/issues/592)) + +1.0.1 / 2015-11-25 +================== +- *erroneous publish* + +1.0.0 / 2015-11-08 +================== +- require `eslint` `v1.0.0` or higher +- remove `babel-eslint` dependency + +0.1.1 / 2015-11-05 +================== +- remove [`id-length`][id-length] rule ([#569](https://github.com/airbnb/javascript/issues/569)) +- enable [`no-mixed-spaces-and-tabs`][no-mixed-spaces-and-tabs] ([#539](https://github.com/airbnb/javascript/issues/539)) +- enable [`no-const-assign`][no-const-assign] ([#560](https://github.com/airbnb/javascript/issues/560)) +- enable [`space-before-keywords`][space-before-keywords] ([#554](https://github.com/airbnb/javascript/issues/554)) + +0.1.0 / 2015-11-05 +================== +- switch to modular rules files courtesy the [eslint-config-default][ecd] project and [@taion][taion]. [PR][pr-modular] +- export `eslint-config-airbnb/legacy` for ES5-only users. `eslint-config-airbnb/legacy` does not require the `babel-eslint` parser. [PR][pr-legacy] + +0.0.9 / 2015-09-24 +================== +- add rule [`no-undef`][no-undef] +- add rule [`id-length`][id-length] + +0.0.8 / 2015-08-21 +================== +- now has a changelog +- now is modular (see instructions above for with react and without react versions) + +0.0.7 / 2015-07-30 +================== +- TODO: fill in + + +[ecd]: https://github.com/walmartlabs/eslint-config-defaults +[taion]: https://github.com/taion +[pr-modular]: https://github.com/airbnb/javascript/pull/526 +[pr-legacy]: https://github.com/airbnb/javascript/pull/527 + +[array-bracket-spacing]: http://eslint.org/docs/rules/array-bracket-spacing +[array-callback-return]: http://eslint.org/docs/rules/array-callback-return +[arrow-body-style]: http://eslint.org/docs/rules/arrow-body-style +[arrow-spacing]: http://eslint.org/docs/rules/arrow-spacing +[computed-property-spacing]: http://eslint.org/docs/rules/computed-property-spacing +[id-length]: http://eslint.org/docs/rules/id-length +[indent]: http://eslint.org/docs/rules/indent +[max-len]: http://eslint.org/docs/rules/max-len +[newline-per-chained-call]: http://eslint.org/docs/rules/newline-per-chained-call +[no-confusing-arrow]: http://eslint.org/docs/rules/no-confusing-arrow +[no-const-assign]: http://eslint.org/docs/rules/no-const-assign +[no-mixed-spaces-and-tabs]: http://eslint.org/docs/rules/no-mixed-spaces-and-tabs +[no-multiple-empty-lines]: http://eslint.org/docs/rules/no-multiple-empty-lines +[no-new-symbol]: http://eslint.org/docs/rules/no-new-symbol +[no-restricted-imports]: http://eslint.org/docs/rules/no-restricted-imports +[no-self-assign]: http://eslint.org/docs/rules/no-self-assign +[no-undef]: http://eslint.org/docs/rules/no-undef +[no-useless-constructor]: http://eslint.org/docs/rules/no-useless-constructor +[no-whitespace-before-property]: http://eslint.org/docs/rules/no-whitespace-before-property +[object-curly-spacing]: http://eslint.org/docs/rules/object-curly-spacing +[object-shorthand]: http://eslint.org/docs/rules/object-shorthand +[one-var-declaration-per-line]: http://eslint.org/docs/rules/one-var-declaration-per-line +[prefer-arrow-callback]: http://eslint.org/docs/rules/prefer-arrow-callback +[prefer-rest-params]: http://eslint.org/docs/rules/prefer-rest-params +[prefer-template]: http://eslint.org/docs/rules/prefer-template +[quote-props]: http://eslint.org/docs/rules/quote-props +[space-before-function-paren]: http://eslint.org/docs/rules/space-before-function-paren +[space-before-keywords]: http://eslint.org/docs/rules/space-before-keywords +[space-in-parens]: http://eslint.org/docs/rules/space-in-parens +[template-curly-spacing]: http://eslint.org/docs/rules/template-curly-spacing + +[react/jsx-space-before-closing]: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-space-before-closing.md +[react/sort-comp]: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-comp.md +[react/display-name]: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md +[react/jsx-no-bind]: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md +[react/no-is-mounted]: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-is-mounted.md +[react/prefer-es6-class]: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md +[react/jsx-quotes]: https://github.com/yannickcr/eslint-plugin-react/blob/f817e37beddddc84b4788969f07c524fa7f0823b/docs/rules/jsx-quotes.md +[react/prefer-stateless-function]: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-stateless-function.md diff --git a/packages/eslint-config-airbnb/README.md b/packages/eslint-config-airbnb/README.md new file mode 100644 index 0000000000..7a0b8c68b6 --- /dev/null +++ b/packages/eslint-config-airbnb/README.md @@ -0,0 +1,49 @@ +# eslint-config-airbnb + +[![npm version](https://badge.fury.io/js/eslint-config-airbnb.svg)](http://badge.fury.io/js/eslint-config-airbnb) + +This package provides Airbnb's .eslintrc as an extensible shared config. + +## Usage + +We export three ESLint configurations for your usage. + +### eslint-config-airbnb + +Our default export contains all of our ESLint rules, including ECMAScript 6+ and React. It requires `eslint`, `eslint-plugin-import`, `eslint-plugin-react`, and `eslint-plugin-jsx-a11y`. + +1. Ensure packages are installed with correct version numbers by running: + ```sh + ( + export PKG=eslint-config-airbnb; + npm info "$PKG" peerDependencies --json | command sed 's/[\{\},]//g ; s/: /@/g' | xargs npm install --save-dev "$PKG" + ) + ``` + + Which produces and runs a command like: + + ```sh + npm install --save-dev eslint-config-airbnb eslint@^2.9.0 eslint-plugin-jsx-a11y@^1.2.0 eslint-plugin-import@^1.7.0 eslint-plugin-react@^5.0.1 + ``` + +2. Add `"extends": "airbnb"` to your .eslintrc + +### eslint-config-airbnb/base + +This entry point is deprecated. See [eslint-config-airbnb-base](https://npmjs.com/eslint-config-airbnb-base). + +### eslint-config-airbnb/legacy + +This entry point is deprecated. See [eslint-config-airbnb-base](https://npmjs.com/eslint-config-airbnb-base). + +See [Airbnb's Javascript styleguide](https://github.com/airbnb/javascript) and +the [ESlint config docs](http://eslint.org/docs/user-guide/configuring#extending-configuration-files) +for more information. + +## Improving this config + +Consider adding test cases if you're making complicated rules changes, like anything involving regexes. Perhaps in a distant future, we could use literate programming to structure our README as test cases for our .eslintrc? + +You can run tests with `npm test`. + +You can make sure this module lints with itself using `npm run lint`. diff --git a/packages/eslint-config-airbnb/base.js b/packages/eslint-config-airbnb/base.js new file mode 100644 index 0000000000..bb1ea39118 --- /dev/null +++ b/packages/eslint-config-airbnb/base.js @@ -0,0 +1,4 @@ +module.exports = { + extends: ['eslint-config-airbnb-base'].map(require.resolve), + rules: {}, +}; diff --git a/packages/eslint-config-airbnb/index.js b/packages/eslint-config-airbnb/index.js new file mode 100644 index 0000000000..ddd3bfb712 --- /dev/null +++ b/packages/eslint-config-airbnb/index.js @@ -0,0 +1,9 @@ +module.exports = { + extends: [ + 'eslint-config-airbnb-base', + 'eslint-config-airbnb-base/rules/strict', + './rules/react', + './rules/react-a11y', + ].map(require.resolve), + rules: {} +}; diff --git a/packages/eslint-config-airbnb/legacy.js b/packages/eslint-config-airbnb/legacy.js new file mode 100644 index 0000000000..e88f71224a --- /dev/null +++ b/packages/eslint-config-airbnb/legacy.js @@ -0,0 +1,4 @@ +module.exports = { + extends: ['eslint-config-airbnb-base/legacy'].map(require.resolve), + rules: {}, +}; diff --git a/packages/eslint-config-airbnb/package.json b/packages/eslint-config-airbnb/package.json new file mode 100644 index 0000000000..c176f07da3 --- /dev/null +++ b/packages/eslint-config-airbnb/package.json @@ -0,0 +1,72 @@ +{ + "name": "eslint-config-airbnb", + "version": "10.0.1", + "description": "Airbnb's ESLint config, following our styleguide", + "main": "index.js", + "scripts": { + "lint": "eslint .", + "tests-only": "babel-tape-runner ./test/test-*.js", + "prepublish": "(in-install || eslint-find-rules --unused) && (not-in-publish || npm test) && safe-publish-latest", + "pretest": "npm run --silent lint", + "test": "npm run --silent tests-only", + "travis": "cd ../eslint-config-airbnb-base && npm install && npm link && cd - && npm link eslint-config-airbnb-base && npm run --silent test ; npm unlink eslint-config-airbnb-base >/dev/null &" + }, + "repository": { + "type": "git", + "url": "https://github.com/airbnb/javascript" + }, + "keywords": [ + "eslint", + "eslintconfig", + "config", + "airbnb", + "javascript", + "styleguide" + ], + "author": "Jake Teton-Landis (https://twitter.com/@jitl)", + "contributors": [ + { + "name": "Jake Teton-Landis", + "url": "https://twitter.com/jitl" + }, + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes/" + }, + { + "name": "Harrison Shoff", + "url": "https://twitter.com/hshoff" + } + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/airbnb/javascript/issues" + }, + "homepage": "https://github.com/airbnb/javascript", + "dependencies": { + "eslint-config-airbnb-base": "^5.0.2" + }, + "devDependencies": { + "babel-preset-airbnb": "^2.0.0", + "babel-tape-runner": "^2.0.1", + "eslint": "^3.3.1", + "eslint-find-rules": "^1.13.0", + "eslint-plugin-import": "^1.13.0", + "eslint-plugin-jsx-a11y": "^2.1.0", + "eslint-plugin-react": "^6.1.2", + "in-publish": "^2.0.0", + "react": ">= 0.13.0", + "safe-publish-latest": "^1.0.1", + "tape": "^4.6.0" + }, + "peerDependencies": { + "eslint": "^3.3.1", + "eslint-plugin-jsx-a11y": "^2.1.0", + "eslint-plugin-import": "^1.13.0", + "eslint-plugin-react": "^6.1.2" + }, + "engines": { + "node": ">= 4" + } +} diff --git a/packages/eslint-config-airbnb/rules/react-a11y.js b/packages/eslint-config-airbnb/rules/react-a11y.js new file mode 100644 index 0000000000..76430261c7 --- /dev/null +++ b/packages/eslint-config-airbnb/rules/react-a11y.js @@ -0,0 +1,105 @@ +module.exports = { + plugins: [ + 'jsx-a11y', + 'react' + ], + ecmaFeatures: { + jsx: true + }, + rules: { + // Enforce that anchors have content + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-has-content.md + // TODO: enable, semver-major + 'jsx-a11y/anchor-has-content': ['off', ['']], + + // Require ARIA roles to be valid and non-abstract + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-role.md + 'jsx-a11y/aria-role': 'error', + + // Enforce all aria-* props are valid. + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-props.md + 'jsx-a11y/aria-props': 'error', + + // Enforce ARIA state and property values are valid. + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-proptypes.md + 'jsx-a11y/aria-proptypes': 'error', + + // Enforce that elements that do not support ARIA roles, states, and + // properties do not have those attributes. + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/aria-unsupported-elements.md + 'jsx-a11y/aria-unsupported-elements': 'error', + + // disallow href "#" + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/href-no-hash.md + 'jsx-a11y/href-no-hash': ['error', ['a']], + + // Require to have a non-empty `alt` prop, or role="presentation" + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/img-has-alt.md + 'jsx-a11y/img-has-alt': 'error', + + // Prevent img alt text from containing redundant words like "image", "picture", or "photo" + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/img-redundant-alt.md + 'jsx-a11y/img-redundant-alt': 'error', + + // require that JSX labels use "htmlFor" + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/label-has-for.md + 'jsx-a11y/label-has-for': ['error', ['label']], + + // require that mouseover/out come with focus/blur, for keyboard-only users + // TODO: evaluate + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/mouse-events-have-key-events.md + 'jsx-a11y/mouse-events-have-key-events': 'off', + + // Prevent use of `accessKey` + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-access-key.md + 'jsx-a11y/no-access-key': 'error', + + // require onBlur instead of onChange + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-onchange.md + 'jsx-a11y/no-onchange': 'off', + + // Enforce that elements with onClick handlers must be focusable. + // TODO: evaluate + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/onclick-has-focus.md + 'jsx-a11y/onclick-has-focus': 'off', + + // require things with onClick to have an aria role + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/onclick-has-role.md + 'jsx-a11y/onclick-has-role': 'off', + + // Enforce that elements with ARIA roles must have all required attributes + // for that role. + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-has-required-aria-props.md + 'jsx-a11y/role-has-required-aria-props': 'error', + + // Enforce that elements with explicit or implicit roles defined contain + // only aria-* properties supported by that role. + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/role-supports-aria-props.md + 'jsx-a11y/role-supports-aria-props': 'error', + + // Enforce tabIndex value is not greater than zero. + // TODO: evaluate + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/tabindex-no-positive.md + 'jsx-a11y/tabindex-no-positive': 'off', + + // ensure tags have content and are not aria-hidden + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/heading-has-content.md + 'jsx-a11y/heading-has-content': ['error', ['']], + + // require HTML elements to have a "lang" prop + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/html-has-lang.md + 'jsx-a11y/html-has-lang': 'error', + + // require HTML element's lang prop to be valid + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/lang.md + 'jsx-a11y/lang': 'error', + + // prevent marquee elements + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-marquee.md + 'jsx-a11y/no-marquee': 'error', + + // only allow to have the "scope" attr + // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/scope.md + 'jsx-a11y/scope': 'error', + }, +}; diff --git a/packages/eslint-config-airbnb/rules/react.js b/packages/eslint-config-airbnb/rules/react.js new file mode 100644 index 0000000000..9921526213 --- /dev/null +++ b/packages/eslint-config-airbnb/rules/react.js @@ -0,0 +1,268 @@ +module.exports = { + plugins: [ + 'react' + ], + parserOptions: { + ecmaFeatures: { + jsx: true, + }, + }, + ecmaFeatures: { + jsx: true + }, + + // View link below for react rules documentation + // https://github.com/yannickcr/eslint-plugin-react#list-of-supported-rules + rules: { + // Specify whether double or single quotes should be used in JSX attributes + // http://eslint.org/docs/rules/jsx-quotes + 'jsx-quotes': ['error', 'prefer-double'], + + // Prevent missing displayName in a React component definition + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md + 'react/display-name': ['off', { ignoreTranspilerName: false }], + + // Forbid certain propTypes (any, array, object) + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-prop-types.md + 'react/forbid-prop-types': ['off', { forbid: ['any', 'array', 'object'] }], + + // Enforce boolean attributes notation in JSX + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md + 'react/jsx-boolean-value': ['error', 'never'], + + // Validate closing bracket location in JSX + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-closing-bracket-location.md + 'react/jsx-closing-bracket-location': ['error', 'line-aligned'], + + // Enforce or disallow spaces inside of curly braces in JSX attributes + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md + 'react/jsx-curly-spacing': ['error', 'never', { allowMultiline: true }], + + // Enforce event handler naming conventions in JSX + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-handler-names.md + 'react/jsx-handler-names': ['off', { + eventHandlerPrefix: 'handle', + eventHandlerPropPrefix: 'on', + }], + + // Validate props indentation in JSX + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent-props.md + 'react/jsx-indent-props': ['error', 2], + + // Validate JSX has key prop when in array or iterator + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-key.md + 'react/jsx-key': 'off', + + // Limit maximum of props on a single line in JSX + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-max-props-per-line.md + 'react/jsx-max-props-per-line': ['off', { maximum: 1 }], + + // Prevent usage of .bind() in JSX props + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md + 'react/jsx-no-bind': ['error', { + ignoreRefs: true, + allowArrowFunctions: true, + allowBind: false, + }], + + // Prevent duplicate props in JSX + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md + 'react/jsx-no-duplicate-props': ['off', { ignoreCase: true }], + + // Prevent usage of unwrapped JSX strings + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-literals.md + 'react/jsx-no-literals': 'off', + + // Disallow undeclared variables in JSX + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-undef.md + 'react/jsx-no-undef': 'error', + + // Enforce PascalCase for user-defined JSX components + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-pascal-case.md + 'react/jsx-pascal-case': ['error', { + allowAllCaps: true, + ignore: [], + }], + + // Enforce propTypes declarations alphabetical sorting + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-prop-types.md + 'react/sort-prop-types': ['off', { + ignoreCase: true, + callbacksLast: false, + requiredFirst: false, + }], + + // Deprecated in favor of react/jsx-sort-props + 'react/jsx-sort-prop-types': 'off', + + // Enforce props alphabetical sorting + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md + 'react/jsx-sort-props': ['off', { + ignoreCase: true, + callbacksLast: false, + shorthandFirst: false, + shorthandLast: false, + }], + + // Prevent React to be incorrectly marked as unused + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-react.md + 'react/jsx-uses-react': ['error'], + + // Prevent variables used in JSX to be incorrectly marked as unused + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-vars.md + 'react/jsx-uses-vars': 'error', + + // Prevent usage of dangerous JSX properties + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger.md + 'react/no-danger': 'off', + + // Prevent usage of deprecated methods + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-deprecated.md + 'react/no-deprecated': ['error'], + + // Prevent usage of setState in componentDidMount + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md + 'react/no-did-mount-set-state': ['error'], + + // Prevent usage of setState in componentDidUpdate + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md + 'react/no-did-update-set-state': ['error'], + + // Prevent direct mutation of this.state + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md + 'react/no-direct-mutation-state': 'off', + + // Prevent usage of isMounted + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-is-mounted.md + 'react/no-is-mounted': 'error', + + // Prevent multiple component definition per file + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-multi-comp.md + 'react/no-multi-comp': ['error', { ignoreStateless: true }], + + // Prevent usage of setState + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-set-state.md + 'react/no-set-state': 'off', + + // Prevent using string references + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md + 'react/no-string-refs': 'error', + + // Prevent usage of unknown DOM property + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unknown-property.md + 'react/no-unknown-property': 'error', + + // Require ES6 class declarations over React.createClass + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md + 'react/prefer-es6-class': ['error', 'always'], + + // Require stateless functions when not using lifecycle methods, setState or ref + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-stateless-function.md + 'react/prefer-stateless-function': 'error', + + // Prevent missing props validation in a React component definition + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md + 'react/prop-types': ['error', { ignore: [], customValidators: [] }], + + // Prevent missing React when using JSX + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md + 'react/react-in-jsx-scope': 'error', + + // Restrict file extensions that may be required + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-extension.md + 'react/require-extension': ['error', { extensions: ['.jsx', '.js'] }], + + // Require render() methods to return something + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-render-return.md + 'react/require-render-return': 'error', + + // Prevent extra closing tags for components without children + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/self-closing-comp.md + 'react/self-closing-comp': 'error', + + // Enforce spaces before the closing bracket of self-closing JSX elements + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-space-before-closing.md + 'react/jsx-space-before-closing': ['error', 'always'], + + // Enforce component methods order + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-comp.md + 'react/sort-comp': ['error', { + order: [ + 'static-methods', + 'lifecycle', + '/^on.+$/', + '/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/', + 'everything-else', + '/^render.+$/', + 'render' + ], + }], + + // Prevent missing parentheses around multilines JSX + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-wrap-multilines.md + 'react/jsx-wrap-multilines': ['error', { + declaration: true, + assignment: true, + return: true + }], + 'react/wrap-multilines': 'off', // deprecated version + + // Require that the first prop in a JSX element be on a new line when the element is multiline + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-first-prop-new-line.md + 'react/jsx-first-prop-new-line': ['error', 'multiline'], + + // Enforce spacing around jsx equals signs + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-equals-spacing.md + 'react/jsx-equals-spacing': ['error', 'never'], + + // Enforce JSX indentation + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent.md + 'react/jsx-indent': ['error', 2], + + // Disallow target="_blank" on links + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-target-blank.md + 'react/jsx-no-target-blank': 'error', + + // only .jsx files may have JSX + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-filename-extension.md + 'react/jsx-filename-extension': ['error', { extensions: ['.jsx'] }], + + // prevent accidental JS comments from being injected into JSX as text + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-comment-textnodes.md + 'react/jsx-no-comment-textnodes': 'error', + 'react/no-comment-textnodes': 'off', // deprecated version + + // disallow using React.render/ReactDOM.render's return value + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-render-return-value.md + 'react/no-render-return-value': 'error', + + // require a shouldComponentUpdate method, or PureRenderMixin + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-optimization.md + 'react/require-optimization': ['off', { allowDecorators: [] }], + + // warn against using findDOMNode() + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-find-dom-node.md + 'react/no-find-dom-node': 'error', + + // Forbid certain props on Components + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-component-props.md + 'react/forbid-component-props': ['off', { forbid: [] }], + + // Prevent problem with children and props.dangerouslySetInnerHTML + // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger-with-children.md + // TODO: enable, semver-major + 'react/no-danger-with-children': 'off', + }, + + settings: { + 'import/resolver': { + node: { + extensions: ['.js', '.jsx', '.json'] + } + }, + react: { + pragma: 'React', + version: '0.14' + }, + } +}; diff --git a/packages/eslint-config-airbnb/test/.eslintrc b/packages/eslint-config-airbnb/test/.eslintrc new file mode 100644 index 0000000000..eafcdbffa6 --- /dev/null +++ b/packages/eslint-config-airbnb/test/.eslintrc @@ -0,0 +1,13 @@ +{ + "rules": { + // disabled because I find it tedious to write tests while following this + // rule + "no-shadow": 0, + + // tests uses `t` for tape + "id-length": [2, {"min": 2, "properties": "never", "exceptions": ["t"]}], + + // tests can import things in devDependencies + "import/no-extraneous-dependencies": [2, {"devDependencies": true}] + } +} diff --git a/packages/eslint-config-airbnb/test/test-base.js b/packages/eslint-config-airbnb/test/test-base.js new file mode 100644 index 0000000000..9457e2ef42 --- /dev/null +++ b/packages/eslint-config-airbnb/test/test-base.js @@ -0,0 +1,33 @@ +import fs from 'fs'; +import path from 'path'; +import test from 'tape'; + +const base = require('../base'); + +const files = { base }; + +fs.readdirSync(path.join(__dirname, '../rules')).forEach(name => { + if (name === 'react.js' || name === 'react-a11y.js') { + return; + } + + files[name] = require(`../rules/${name}`); // eslint-disable-line global-require +}); + +Object.keys(files).forEach(name => { + const config = files[name]; + + test(`${name}: does not reference react`, t => { + t.plan(2); + + // scan plugins for react and fail if it is found + const hasReactPlugin = Object.prototype.hasOwnProperty.call(config, 'plugins') && + config.plugins.indexOf('react') !== -1; + t.notOk(hasReactPlugin, 'there is no react plugin'); + + // scan rules for react/ and fail if any exist + const reactRuleIds = Object.keys(config.rules) + .filter(ruleId => ruleId.indexOf('react/') === 0); + t.deepEquals(reactRuleIds, [], 'there are no react/ rules'); + }); +}); diff --git a/packages/eslint-config-airbnb/test/test-react-order.js b/packages/eslint-config-airbnb/test/test-react-order.js new file mode 100644 index 0000000000..37d417ca15 --- /dev/null +++ b/packages/eslint-config-airbnb/test/test-react-order.js @@ -0,0 +1,93 @@ +import test from 'tape'; +import { CLIEngine } from 'eslint'; +import eslintrc from '../'; +import reactRules from '../rules/react'; +import reactA11yRules from '../rules/react-a11y'; + +const cli = new CLIEngine({ + useEslintrc: false, + baseConfig: eslintrc, + + rules: { + // It is okay to import devDependencies in tests. + 'import/no-extraneous-dependencies': [2, { devDependencies: true }], + }, +}); + +function lint(text) { + // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles + // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext + const linter = cli.executeOnText(text); + return linter.results[0]; +} + +function wrapComponent(body) { + return ` +import React from 'react'; + +export default class MyComponent extends React.Component { +/* eslint no-empty-function: 0 */ +${body} +} +`; +} + +test('validate react prop order', (t) => { + t.test('make sure our eslintrc has React and JSX linting dependencies', (t) => { + t.plan(2); + t.deepEqual(reactRules.plugins, ['react']); + t.deepEqual(reactA11yRules.plugins, ['jsx-a11y', 'react']); + }); + + t.test('passes a good component', (t) => { + t.plan(3); + const result = lint(wrapComponent(` + componentWillMount() {} + componentDidMount() {} + setFoo() {} + getFoo() {} + setBar() {} + someMethod() {} + renderDogs() {} + render() { return
; } +`)); + + t.notOk(result.warningCount, 'no warnings'); + t.notOk(result.errorCount, 'no errors'); + t.deepEquals(result.messages, [], 'no messages in results'); + }); + + t.test('order: when random method is first', t => { + t.plan(2); + const result = lint(wrapComponent(` + someMethod() {} + componentWillMount() {} + componentDidMount() {} + setFoo() {} + getFoo() {} + setBar() {} + renderDogs() {} + render() { return
; } +`)); + + t.ok(result.errorCount, 'fails'); + t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort'); + }); + + t.test('order: when random method after lifecycle methods', t => { + t.plan(2); + const result = lint(wrapComponent(` + componentWillMount() {} + componentDidMount() {} + someMethod() {} + setFoo() {} + getFoo() {} + setBar() {} + renderDogs() {} + render() { return
; } +`)); + + t.ok(result.errorCount, 'fails'); + t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort'); + }); +}); diff --git a/react/README.md b/react/README.md new file mode 100644 index 0000000000..32e4be48ab --- /dev/null +++ b/react/README.md @@ -0,0 +1,581 @@ +# Airbnb React/JSX Style Guide + +*A mostly reasonable approach to React and JSX* + +## Table of Contents + + 1. [Basic Rules](#basic-rules) + 1. [Class vs `React.createClass` vs stateless](#class-vs-reactcreateclass-vs-stateless) + 1. [Naming](#naming) + 1. [Declaration](#declaration) + 1. [Alignment](#alignment) + 1. [Quotes](#quotes) + 1. [Spacing](#spacing) + 1. [Props](#props) + 1. [Refs](#refs) + 1. [Parentheses](#parentheses) + 1. [Tags](#tags) + 1. [Methods](#methods) + 1. [Ordering](#ordering) + 1. [`isMounted`](#ismounted) + +## Basic Rules + + - Only include one React component per file. + - However, multiple [Stateless, or Pure, Components](https://facebook.github.io/react/docs/reusable-components.html#stateless-functions) are allowed per file. eslint: [`react/no-multi-comp`](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-multi-comp.md#ignorestateless). + - Always use JSX syntax. + - Do not use `React.createElement` unless you're initializing the app from a file that is not JSX. + +## Class vs `React.createClass` vs stateless + + - If you have internal state and/or refs, prefer `class extends React.Component` over `React.createClass` unless you have a very good reason to use mixins. eslint: [`react/prefer-es6-class`](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md) [`react/prefer-stateless-function`](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-stateless-function.md) + + ```jsx + // bad + const Listing = React.createClass({ + // ... + render() { + return
{this.state.hello}
; + } + }); + + // good + class Listing extends React.Component { + // ... + render() { + return
{this.state.hello}
; + } + } + ``` + + And if you don't have state or refs, prefer normal functions (not arrow functions) over classes: + + ```jsx + // bad + class Listing extends React.Component { + render() { + return
{this.props.hello}
; + } + } + + // bad (relying on function name inference is discouraged) + const Listing = ({ hello }) => ( +
{hello}
+ ); + + // good + function Listing({ hello }) { + return
{hello}
; + } + ``` + +## Naming + + - **Extensions**: Use `.jsx` extension for React components. + - **Filename**: Use PascalCase for filenames. E.g., `ReservationCard.jsx`. + - **Reference Naming**: Use PascalCase for React components and camelCase for their instances. eslint: [`react/jsx-pascal-case`](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-pascal-case.md) + + ```jsx + // bad + import reservationCard from './ReservationCard'; + + // good + import ReservationCard from './ReservationCard'; + + // bad + const ReservationItem = ; + + // good + const reservationItem = ; + ``` + + - **Component Naming**: Use the filename as the component name. For example, `ReservationCard.jsx` should have a reference name of `ReservationCard`. However, for root components of a directory, use `index.jsx` as the filename and use the directory name as the component name: + + ```jsx + // bad + import Footer from './Footer/Footer'; + + // bad + import Footer from './Footer/index'; + + // good + import Footer from './Footer'; + ``` + - **Higher-order Component Naming**: Use a composite of the higher-order component's name and the passed-in component's name as the `displayName` on the generated component. For example, the higher-order component `withFoo()`, when passed a component `Bar` should produce a component with a `displayName` of `withFoo(Bar)`. + + > Why? A component's `displayName` may be used by developer tools or in error messages, and having a value that clearly expresses this relationship helps people understand what is happening. + + ```jsx + // bad + export default function withFoo(WrappedComponent) { + return function WithFoo(props) { + return ; + } + } + + // good + export default function withFoo(WrappedComponent) { + function WithFoo(props) { + return ; + } + + const wrappedComponentName = WrappedComponent.displayName + || WrappedComponent.name + || 'Component'; + + WithFoo.displayName = `withFoo(${wrappedComponentName})`; + return WithFoo; + } + ``` +## Declaration + + - Do not use `displayName` for naming components. Instead, name the component by reference. + + ```jsx + // bad + export default React.createClass({ + displayName: 'ReservationCard', + // stuff goes here + }); + + // good + export default class ReservationCard extends React.Component { + } + ``` + +## Alignment + + - Follow these alignment styles for JSX syntax. eslint: [`react/jsx-closing-bracket-location`](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-closing-bracket-location.md) + + ```jsx + // bad + + + // good + + + // if props fit in one line then keep it on the same line + + + // children get indented normally + + + + ``` + +## Quotes + + - Always use double quotes (`"`) for JSX attributes, but single quotes for all other JS. eslint: [`jsx-quotes`](http://eslint.org/docs/rules/jsx-quotes) + + > Why? JSX attributes [can't contain escaped quotes](http://eslint.org/docs/rules/jsx-quotes), so double quotes make contractions like `"don't"` easier to type. + > Regular HTML attributes also typically use double quotes instead of single, so JSX attributes mirror this convention. + + ```jsx + // bad + + + // good + + + // bad + + + // good + + ``` + +## Spacing + + - Always include a single space in your self-closing tag. + + ```jsx + // bad + + + // very bad + + + // bad + + + // good + + ``` + + - Do not pad JSX curly braces with spaces. eslint: [`react/jsx-curly-spacing`](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md) + + ```jsx + // bad + + + // good + + ``` + +## Props + + - Always use camelCase for prop names. + + ```jsx + // bad + + + // good + + ``` + + - Omit the value of the prop when it is explicitly `true`. eslint: [`react/jsx-boolean-value`](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md) + + ```jsx + // bad +