├── .gitignore
├── README.md
├── es5
└── README.md
├── linters
├── .eslintrc
├── README.md
├── SublimeLinter
│ └── SublimeLinter.sublime-settings
└── jshintrc
├── package.json
├── packages
└── eslint-config-airbnb
│ ├── .eslintrc
│ ├── README.md
│ ├── base
│ └── index.js
│ ├── index.js
│ ├── node_modules
│ └── eslint-config-airbnb
│ ├── package.json
│ ├── react.js
│ └── test
│ ├── test-base.js
│ └── test-react-order.js
└── react
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Class Free JavaScript Style Guide() {
2 |
3 | *A mostly reasonable fork of the AirBnB JavaScript Style Guide*
4 |
5 | Virtually identical, with the following **very important exceptions:**
6 |
7 | * Reverse the advice about `class` and `extends`. Instead, favor factory functions and prototypal object composition.
8 | * Don't use `_` for `_privateProperties`. Use closures, instead, for true data privacy and a self-documenting API.
9 |
10 |
11 | [](https://www.npmjs.com/package/eslint-config-airbnb)
12 | [](https://gitter.im/airbnb/javascript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
13 |
14 | Other Style Guides
15 | - [ES5](es5/)
16 | - [React](react/)
17 | - [CSS & Sass](https://github.com/airbnb/css)
18 | - [Ruby](https://github.com/airbnb/ruby)
19 |
20 | ## Table of Contents
21 |
22 | 1. [Types](#types)
23 | 1. [References](#references)
24 | 1. [Objects](#objects)
25 | 1. [Arrays](#arrays)
26 | 1. [Destructuring](#destructuring)
27 | 1. [Strings](#strings)
28 | 1. [Functions](#functions)
29 | 1. [Arrow Functions](#arrow-functions)
30 | 1. [Constructors](#constructors)
31 | 1. [Modules](#modules)
32 | 1. [Iterators and Generators](#iterators-and-generators)
33 | 1. [Properties](#properties)
34 | 1. [Variables](#variables)
35 | 1. [Hoisting](#hoisting)
36 | 1. [Comparison Operators & Equality](#comparison-operators--equality)
37 | 1. [Blocks](#blocks)
38 | 1. [Comments](#comments)
39 | 1. [Whitespace](#whitespace)
40 | 1. [Commas](#commas)
41 | 1. [Semicolons](#semicolons)
42 | 1. [Type Casting & Coercion](#type-casting--coercion)
43 | 1. [Naming Conventions](#naming-conventions)
44 | 1. [Accessors](#accessors)
45 | 1. [Events](#events)
46 | 1. [jQuery](#jquery)
47 | 1. [ECMAScript 5 Compatibility](#ecmascript-5-compatibility)
48 | 1. [ECMAScript 6 Styles](#ecmascript-6-styles)
49 | 1. [Testing](#testing)
50 | 1. [Performance](#performance)
51 | 1. [Resources](#resources)
52 | 1. [In the Wild](#in-the-wild)
53 | 1. [Translation](#translation)
54 | 1. [The JavaScript Style Guide Guide](#the-javascript-style-guide-guide)
55 | 1. [Chat With Us About JavaScript](#chat-with-us-about-javascript)
56 | 1. [Contributors](#contributors)
57 | 1. [License](#license)
58 |
59 | ## Types
60 |
61 | - [1.1](#1.1) **Primitives**: When you access a primitive type you work directly on its value.
62 |
63 | + `string`
64 | + `number`
65 | + `boolean`
66 | + `null`
67 | + `undefined`
68 |
69 | ```javascript
70 | const foo = 1;
71 | let bar = foo;
72 |
73 | bar = 9;
74 |
75 | console.log(foo, bar); // => 1, 9
76 | ```
77 | - [1.2](#1.2) **Complex**: When you access a complex type you work on a reference to its value.
78 |
79 | + `object`
80 | + `array`
81 | + `function`
82 |
83 | ```javascript
84 | const foo = [1, 2];
85 | const bar = foo;
86 |
87 | bar[0] = 9;
88 |
89 | console.log(foo[0], bar[0]); // => 9, 9
90 | ```
91 |
92 | **[⬆ back to top](#table-of-contents)**
93 |
94 | ## References
95 |
96 | - [2.1](#2.1) Use `const` for all of your references; avoid using `var`.
97 |
98 | > Why? This ensures that you can't reassign your references (mutation), which can lead to bugs and difficult to comprehend code.
99 |
100 | ```javascript
101 | // bad
102 | var a = 1;
103 | var b = 2;
104 |
105 | // good
106 | const a = 1;
107 | const b = 2;
108 | ```
109 |
110 | - [2.2](#2.2) If you must mutate references, use `let` instead of `var`.
111 |
112 | > Why? `let` is block-scoped rather than function-scoped like `var`.
113 |
114 | ```javascript
115 | // bad
116 | var count = 1;
117 | if (true) {
118 | count += 1;
119 | }
120 |
121 | // good, use the let.
122 | let count = 1;
123 | if (true) {
124 | count += 1;
125 | }
126 | ```
127 |
128 | - [2.3](#2.3) Note that both `let` and `const` are block-scoped.
129 |
130 | ```javascript
131 | // const and let only exist in the blocks they are defined in.
132 | {
133 | let a = 1;
134 | const b = 1;
135 | }
136 | console.log(a); // ReferenceError
137 | console.log(b); // ReferenceError
138 | ```
139 |
140 | **[⬆ back to top](#table-of-contents)**
141 |
142 | ## Objects
143 |
144 | - [3.1](#3.1) Use the literal syntax for object creation.
145 |
146 | ```javascript
147 | // bad
148 | const item = new Object();
149 |
150 | // good
151 | const item = {};
152 | ```
153 |
154 | - [3.2](#3.2) If your code will be executed in browsers in script context, 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). It’s OK to use them in ES6 modules and server-side code.
155 |
156 | ```javascript
157 | // bad
158 | const superman = {
159 | default: { clark: 'kent' },
160 | private: true,
161 | };
162 |
163 | // good
164 | const superman = {
165 | defaults: { clark: 'kent' },
166 | hidden: true,
167 | };
168 | ```
169 |
170 | - [3.3](#3.3) Use readable synonyms in place of reserved words.
171 |
172 | ```javascript
173 | // bad
174 | const superman = {
175 | class: 'alien',
176 | };
177 |
178 | // bad
179 | const superman = {
180 | klass: 'alien',
181 | };
182 |
183 | // good
184 | const superman = {
185 | type: 'alien',
186 | };
187 | ```
188 |
189 |
190 | - [3.4](#3.4) Use computed property names when creating objects with dynamic property names.
191 |
192 | > Why? They allow you to define all the properties of an object in one place.
193 |
194 | ```javascript
195 |
196 | function getKey(k) {
197 | return `a key named ${k}`;
198 | }
199 |
200 | // bad
201 | const obj = {
202 | id: 5,
203 | name: 'San Francisco',
204 | };
205 | obj[getKey('enabled')] = true;
206 |
207 | // good
208 | const obj = {
209 | id: 5,
210 | name: 'San Francisco',
211 | [getKey('enabled')]: true,
212 | };
213 | ```
214 |
215 |
216 | - [3.5](#3.5) Use object method shorthand.
217 |
218 | ```javascript
219 | // bad
220 | const atom = {
221 | value: 1,
222 |
223 | addValue: function (value) {
224 | return atom.value + value;
225 | },
226 | };
227 |
228 | // good
229 | const atom = {
230 | value: 1,
231 |
232 | addValue(value) {
233 | return atom.value + value;
234 | },
235 | };
236 | ```
237 |
238 |
239 | - [3.6](#3.6) Use property value shorthand.
240 |
241 | > Why? It is shorter to write and descriptive.
242 |
243 | ```javascript
244 | const lukeSkywalker = 'Luke Skywalker';
245 |
246 | // bad
247 | const obj = {
248 | lukeSkywalker: lukeSkywalker,
249 | };
250 |
251 | // good
252 | const obj = {
253 | lukeSkywalker,
254 | };
255 | ```
256 |
257 | - [3.7](#3.7) Group your shorthand properties at the beginning of your object declaration.
258 |
259 | > Why? It's easier to tell which properties are using the shorthand.
260 |
261 | ```javascript
262 | const anakinSkywalker = 'Anakin Skywalker';
263 | const lukeSkywalker = 'Luke Skywalker';
264 |
265 | // bad
266 | const obj = {
267 | episodeOne: 1,
268 | twoJediWalkIntoACantina: 2,
269 | lukeSkywalker,
270 | episodeThree: 3,
271 | mayTheFourth: 4,
272 | anakinSkywalker,
273 | };
274 |
275 | // good
276 | const obj = {
277 | lukeSkywalker,
278 | anakinSkywalker,
279 | episodeOne: 1,
280 | twoJediWalkIntoACantina: 2,
281 | episodeThree: 3,
282 | mayTheFourth: 4,
283 | };
284 | ```
285 |
286 | **[⬆ back to top](#table-of-contents)**
287 |
288 | ## Arrays
289 |
290 | - [4.1](#4.1) Use the literal syntax for array creation.
291 |
292 | ```javascript
293 | // bad
294 | const items = new Array();
295 |
296 | // good
297 | const items = [];
298 | ```
299 |
300 | - [4.2](#4.2) Use Array#push instead of direct assignment to add items to an array.
301 |
302 | ```javascript
303 | const someStack = [];
304 |
305 | // bad
306 | someStack[someStack.length] = 'abracadabra';
307 |
308 | // good
309 | someStack.push('abracadabra');
310 | ```
311 |
312 |
313 | - [4.3](#4.3) Use array spreads `...` to copy arrays.
314 |
315 | ```javascript
316 | // bad
317 | const len = items.length;
318 | const itemsCopy = [];
319 | let i;
320 |
321 | for (i = 0; i < len; i++) {
322 | itemsCopy[i] = items[i];
323 | }
324 |
325 | // good
326 | const itemsCopy = [...items];
327 | ```
328 | - [4.4](#4.4) To convert an array-like object to an array, use Array#from.
329 |
330 | ```javascript
331 | const foo = document.querySelectorAll('.foo');
332 | const nodes = Array.from(foo);
333 | ```
334 |
335 | **[⬆ back to top](#table-of-contents)**
336 |
337 | ## Destructuring
338 |
339 | - [5.1](#5.1) Use object destructuring when accessing and using multiple properties of an object.
340 |
341 | > Why? Destructuring saves you from creating temporary references for those properties.
342 |
343 | ```javascript
344 | // bad
345 | function getFullName(user) {
346 | const firstName = user.firstName;
347 | const lastName = user.lastName;
348 |
349 | return `${firstName} ${lastName}`;
350 | }
351 |
352 | // good
353 | function getFullName(obj) {
354 | const { firstName, lastName } = obj;
355 | return `${firstName} ${lastName}`;
356 | }
357 |
358 | // best
359 | function getFullName({ firstName, lastName }) {
360 | return `${firstName} ${lastName}`;
361 | }
362 | ```
363 |
364 | - [5.2](#5.2) Use array destructuring.
365 |
366 | ```javascript
367 | const arr = [1, 2, 3, 4];
368 |
369 | // bad
370 | const first = arr[0];
371 | const second = arr[1];
372 |
373 | // good
374 | const [first, second] = arr;
375 | ```
376 |
377 | - [5.3](#5.3) Use object destructuring for multiple return values, not array destructuring.
378 |
379 | > Why? You can add new properties over time or change the order of things without breaking call sites.
380 |
381 | ```javascript
382 | // bad
383 | function processInput(input) {
384 | // then a miracle occurs
385 | return [left, right, top, bottom];
386 | }
387 |
388 | // the caller needs to think about the order of return data
389 | const [left, __, top] = processInput(input);
390 |
391 | // good
392 | function processInput(input) {
393 | // then a miracle occurs
394 | return { left, right, top, bottom };
395 | }
396 |
397 | // the caller selects only the data they need
398 | const { left, right } = processInput(input);
399 | ```
400 |
401 |
402 | **[⬆ back to top](#table-of-contents)**
403 |
404 | ## Strings
405 |
406 | - [6.1](#6.1) Use single quotes `''` for strings.
407 |
408 | ```javascript
409 | // bad
410 | const name = "Capt. Janeway";
411 |
412 | // good
413 | const name = 'Capt. Janeway';
414 | ```
415 |
416 | - [6.2](#6.2) Strings longer than 100 characters should be written across multiple lines using string concatenation.
417 | - [6.3](#6.3) 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).
418 |
419 | ```javascript
420 | // bad
421 | 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.';
422 |
423 | // bad
424 | const errorMessage = 'This is a super long error that was thrown because \
425 | of Batman. When you stop to think about how Batman had anything to do \
426 | with this, you would get nowhere \
427 | fast.';
428 |
429 | // good
430 | const errorMessage = 'This is a super long error that was thrown because ' +
431 | 'of Batman. When you stop to think about how Batman had anything to do ' +
432 | 'with this, you would get nowhere fast.';
433 | ```
434 |
435 |
436 | - [6.4](#6.4) When programmatically building up strings, use template strings instead of concatenation.
437 |
438 | > Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.
439 |
440 | ```javascript
441 | // bad
442 | function sayHi(name) {
443 | return 'How are you, ' + name + '?';
444 | }
445 |
446 | // bad
447 | function sayHi(name) {
448 | return ['How are you, ', name, '?'].join();
449 | }
450 |
451 | // good
452 | function sayHi(name) {
453 | return `How are you, ${name}?`;
454 | }
455 | ```
456 | - [6.5](#6.5) Never use eval() on a string, it opens too many vulnerabilities.
457 |
458 | **[⬆ back to top](#table-of-contents)**
459 |
460 |
461 | ## Functions
462 |
463 | - [7.1](#7.1) Use function declarations instead of function expressions.
464 |
465 | > 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.
466 |
467 | ```javascript
468 | // bad
469 | const foo = function () {
470 | };
471 |
472 | // good
473 | function foo() {
474 | }
475 | ```
476 |
477 | - [7.2](#7.2) Function expressions:
478 |
479 | ```javascript
480 | // immediately-invoked function expression (IIFE)
481 | (() => {
482 | console.log('Welcome to the Internet. Please follow me.');
483 | })();
484 | ```
485 |
486 | - [7.3](#7.3) Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears.
487 | - [7.4](#7.4) **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).
488 |
489 | ```javascript
490 | // bad
491 | if (currentUser) {
492 | function test() {
493 | console.log('Nope.');
494 | }
495 | }
496 |
497 | // good
498 | let test;
499 | if (currentUser) {
500 | test = () => {
501 | console.log('Yup.');
502 | };
503 | }
504 | ```
505 |
506 | - [7.5](#7.5) Never name a parameter `arguments`. This will take precedence over the `arguments` object that is given to every function scope.
507 |
508 | ```javascript
509 | // bad
510 | function nope(name, options, arguments) {
511 | // ...stuff...
512 | }
513 |
514 | // good
515 | function yup(name, options, args) {
516 | // ...stuff...
517 | }
518 | ```
519 |
520 |
521 | - [7.6](#7.6) Never use `arguments`, opt to use rest syntax `...` instead.
522 |
523 | > Why? `...` is explicit about which arguments you want pulled. Plus rest arguments are a real Array and not Array-like like `arguments`.
524 |
525 | ```javascript
526 | // bad
527 | function concatenateAll() {
528 | const args = Array.prototype.slice.call(arguments);
529 | return args.join('');
530 | }
531 |
532 | // good
533 | function concatenateAll(...args) {
534 | return args.join('');
535 | }
536 | ```
537 |
538 |
539 | - [7.7](#7.7) Use default parameter syntax rather than mutating function arguments.
540 |
541 | ```javascript
542 | // really bad
543 | function handleThings(opts) {
544 | // No! We shouldn't mutate function arguments.
545 | // Double bad: if opts is falsy it'll be set to an object which may
546 | // be what you want but it can introduce subtle bugs.
547 | opts = opts || {};
548 | // ...
549 | }
550 |
551 | // still bad
552 | function handleThings(opts) {
553 | if (opts === void 0) {
554 | opts = {};
555 | }
556 | // ...
557 | }
558 |
559 | // good
560 | function handleThings(opts = {}) {
561 | // ...
562 | }
563 | ```
564 |
565 | - [7.8](#7.8) Avoid side effects with default parameters
566 |
567 | > Why? They are confusing to reason about.
568 |
569 | ```javascript
570 | var b = 1;
571 | // bad
572 | function count(a = b++) {
573 | console.log(a);
574 | }
575 | count(); // 1
576 | count(); // 2
577 | count(3); // 3
578 | count(); // 3
579 | ```
580 |
581 | - [7.9](#7.9) Never use the Function constructor to create a new function.
582 |
583 | > Why? Creating a function in this way evaluates a string similarly to eval(), which opens vulnerabilities.
584 |
585 | ```javascript
586 | // bad
587 | var add = new Function('a', 'b', 'return a + b');
588 |
589 | // still bad
590 | var subtract = Function('a', 'b', 'return a - b');
591 | ```
592 |
593 | **[⬆ back to top](#table-of-contents)**
594 |
595 | ## Arrow Functions
596 |
597 | - [8.1](#8.1) When you must use function expressions (as when passing an anonymous function), use arrow function notation.
598 |
599 | > 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.
600 |
601 | > Why not? If you have a fairly complicated function, you might move that logic out into its own function declaration.
602 |
603 | ```javascript
604 | // bad
605 | [1, 2, 3].map(function (x) {
606 | const y = x + 1;
607 | return x * y;
608 | });
609 |
610 | // good
611 | [1, 2, 3].map((x) => {
612 | const y = x + 1;
613 | return x * y;
614 | });
615 | ```
616 |
617 | - [8.2](#8.2) If the function body consists of a single expression, feel free to omit the braces and use the implicit return. Otherwise use a `return` statement.
618 |
619 | > Why? Syntactic sugar. It reads well when multiple functions are chained together.
620 |
621 | > Why not? If you plan on returning an object.
622 |
623 | ```javascript
624 | // good
625 | [1, 2, 3].map(number => `A string containing the ${number}.`);
626 |
627 | // bad
628 | [1, 2, 3].map(number => {
629 | const nextNumber = number + 1;
630 | `A string containing the ${nextNumber}.`;
631 | });
632 |
633 | // good
634 | [1, 2, 3].map(number => {
635 | const nextNumber = number + 1;
636 | return `A string containing the ${nextNumber}.`;
637 | });
638 | ```
639 |
640 | - [8.3](#8.3) In case the expression spans over multiple lines, wrap it in parentheses for better readability.
641 |
642 | > Why? It shows clearly where the function starts and ends.
643 |
644 | ```js
645 | // bad
646 | [1, 2, 3].map(number => 'As time went by, the string containing the ' +
647 | `${number} became much longer. So we needed to break it over multiple ` +
648 | 'lines.'
649 | );
650 |
651 | // good
652 | [1, 2, 3].map(number => (
653 | `As time went by, the string containing the ${number} became much ` +
654 | 'longer. So we needed to break it over multiple lines.'
655 | ));
656 | ```
657 |
658 |
659 | - [8.4](#8.4) If your function only takes a single argument, feel free to omit the parentheses.
660 |
661 | > Why? Less visual clutter.
662 |
663 | ```js
664 | // good
665 | [1, 2, 3].map(x => x * x);
666 |
667 | // good
668 | [1, 2, 3].reduce((y, x) => x + y);
669 | ```
670 |
671 | **[⬆ back to top](#table-of-contents)**
672 |
673 |
674 | ## Constructors
675 |
676 | - [9.1](#9.1) Always use `class`. Avoid manipulating `prototype` directly.
677 |
678 | > Why? `class` syntax is more concise and easier to reason about.
679 |
680 | ```javascript
681 | // bad
682 | function Queue(contents = []) {
683 | this._queue = [...contents];
684 | }
685 | Queue.prototype.pop = function() {
686 | const value = this._queue[0];
687 | this._queue.splice(0, 1);
688 | return value;
689 | }
690 |
691 |
692 | // good
693 | class Queue {
694 | constructor(contents = []) {
695 | this._queue = [...contents];
696 | }
697 | pop() {
698 | const value = this._queue[0];
699 | this._queue.splice(0, 1);
700 | return value;
701 | }
702 | }
703 | ```
704 |
705 | - [9.2](#9.2) Use `extends` for inheritance.
706 |
707 | > Why? It is a built-in way to inherit prototype functionality without breaking `instanceof`.
708 |
709 | ```javascript
710 | // bad
711 | const inherits = require('inherits');
712 | function PeekableQueue(contents) {
713 | Queue.apply(this, contents);
714 | }
715 | inherits(PeekableQueue, Queue);
716 | PeekableQueue.prototype.peek = function() {
717 | return this._queue[0];
718 | }
719 |
720 | // good
721 | class PeekableQueue extends Queue {
722 | peek() {
723 | return this._queue[0];
724 | }
725 | }
726 | ```
727 |
728 | - [9.3](#9.3) Methods can return `this` to help with method chaining.
729 |
730 | ```javascript
731 | // bad
732 | Jedi.prototype.jump = function() {
733 | this.jumping = true;
734 | return true;
735 | };
736 |
737 | Jedi.prototype.setHeight = function(height) {
738 | this.height = height;
739 | };
740 |
741 | const luke = new Jedi();
742 | luke.jump(); // => true
743 | luke.setHeight(20); // => undefined
744 |
745 | // good
746 | class Jedi {
747 | jump() {
748 | this.jumping = true;
749 | return this;
750 | }
751 |
752 | setHeight(height) {
753 | this.height = height;
754 | return this;
755 | }
756 | }
757 |
758 | const luke = new Jedi();
759 |
760 | luke.jump()
761 | .setHeight(20);
762 | ```
763 |
764 |
765 | - [9.4](#9.4) It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.
766 |
767 | ```javascript
768 | class Jedi {
769 | constructor(options = {}) {
770 | this.name = options.name || 'no name';
771 | }
772 |
773 | getName() {
774 | return this.name;
775 | }
776 |
777 | toString() {
778 | return `Jedi - ${this.getName()}`;
779 | }
780 | }
781 | ```
782 |
783 | **[⬆ back to top](#table-of-contents)**
784 |
785 |
786 | ## Modules
787 |
788 | - [10.1](#10.1) Always use modules (`import`/`export`) over a non-standard module system. You can always transpile to your preferred module system.
789 |
790 | > Why? Modules are the future, let's start using the future now.
791 |
792 | ```javascript
793 | // bad
794 | const AirbnbStyleGuide = require('./AirbnbStyleGuide');
795 | module.exports = AirbnbStyleGuide.es6;
796 |
797 | // ok
798 | import AirbnbStyleGuide from './AirbnbStyleGuide';
799 | export default AirbnbStyleGuide.es6;
800 |
801 | // best
802 | import { es6 } from './AirbnbStyleGuide';
803 | export default es6;
804 | ```
805 |
806 | - [10.2](#10.2) Do not use wildcard imports.
807 |
808 | > Why? This makes sure you have a single default export.
809 |
810 | ```javascript
811 | // bad
812 | import * as AirbnbStyleGuide from './AirbnbStyleGuide';
813 |
814 | // good
815 | import AirbnbStyleGuide from './AirbnbStyleGuide';
816 | ```
817 |
818 | - [10.3](#10.3) And do not export directly from an import.
819 |
820 | > Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent.
821 |
822 | ```javascript
823 | // bad
824 | // filename es6.js
825 | export { es6 as default } from './airbnbStyleGuide';
826 |
827 | // good
828 | // filename es6.js
829 | import { es6 } from './AirbnbStyleGuide';
830 | export default es6;
831 | ```
832 |
833 | **[⬆ back to top](#table-of-contents)**
834 |
835 | ## Iterators and Generators
836 |
837 | - [11.1](#11.1) Don't use iterators. Prefer JavaScript's higher-order functions like `map()` and `reduce()` instead of loops like `for-of`.
838 |
839 | > Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side-effects.
840 |
841 | ```javascript
842 | const numbers = [1, 2, 3, 4, 5];
843 |
844 | // bad
845 | let sum = 0;
846 | for (let num of numbers) {
847 | sum += num;
848 | }
849 |
850 | sum === 15;
851 |
852 | // good
853 | let sum = 0;
854 | numbers.forEach((num) => sum += num);
855 | sum === 15;
856 |
857 | // best (use the functional force)
858 | const sum = numbers.reduce((total, num) => total + num, 0);
859 | sum === 15;
860 | ```
861 |
862 | - [11.2](#11.2) Don't use generators for now.
863 |
864 | > Why? They don't transpile well to ES5.
865 |
866 | **[⬆ back to top](#table-of-contents)**
867 |
868 |
869 | ## Properties
870 |
871 | - [12.1](#12.1) Use dot notation when accessing properties.
872 |
873 | ```javascript
874 | const luke = {
875 | jedi: true,
876 | age: 28,
877 | };
878 |
879 | // bad
880 | const isJedi = luke['jedi'];
881 |
882 | // good
883 | const isJedi = luke.jedi;
884 | ```
885 |
886 | - [12.2](#12.2) Use subscript notation `[]` when accessing properties with a variable.
887 |
888 | ```javascript
889 | const luke = {
890 | jedi: true,
891 | age: 28,
892 | };
893 |
894 | function getProp(prop) {
895 | return luke[prop];
896 | }
897 |
898 | const isJedi = getProp('jedi');
899 | ```
900 |
901 | **[⬆ back to top](#table-of-contents)**
902 |
903 |
904 | ## Variables
905 |
906 | - [13.1](#13.1) 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.
907 |
908 | ```javascript
909 | // bad
910 | superPower = new SuperPower();
911 |
912 | // good
913 | const superPower = new SuperPower();
914 | ```
915 |
916 | - [13.2](#13.2) Use one `const` declaration per variable.
917 |
918 | > 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.
919 |
920 | ```javascript
921 | // bad
922 | const items = getItems(),
923 | goSportsTeam = true,
924 | dragonball = 'z';
925 |
926 | // bad
927 | // (compare to above, and try to spot the mistake)
928 | const items = getItems(),
929 | goSportsTeam = true;
930 | dragonball = 'z';
931 |
932 | // good
933 | const items = getItems();
934 | const goSportsTeam = true;
935 | const dragonball = 'z';
936 | ```
937 |
938 | - [13.3](#13.3) Group all your `const`s and then group all your `let`s.
939 |
940 | > Why? This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
941 |
942 | ```javascript
943 | // bad
944 | let i, len, dragonball,
945 | items = getItems(),
946 | goSportsTeam = true;
947 |
948 | // bad
949 | let i;
950 | const items = getItems();
951 | let dragonball;
952 | const goSportsTeam = true;
953 | let len;
954 |
955 | // good
956 | const goSportsTeam = true;
957 | const items = getItems();
958 | let dragonball;
959 | let i;
960 | let length;
961 | ```
962 |
963 | - [13.4](#13.4) Assign variables where you need them, but place them in a reasonable place.
964 |
965 | > Why? `let` and `const` are block scoped and not function scoped.
966 |
967 | ```javascript
968 | // good
969 | function() {
970 | test();
971 | console.log('doing stuff..');
972 |
973 | //..other stuff..
974 |
975 | const name = getName();
976 |
977 | if (name === 'test') {
978 | return false;
979 | }
980 |
981 | return name;
982 | }
983 |
984 | // bad - unnecessary function call
985 | function(hasName) {
986 | const name = getName();
987 |
988 | if (!hasName) {
989 | return false;
990 | }
991 |
992 | this.setFirstName(name);
993 |
994 | return true;
995 | }
996 |
997 | // good
998 | function(hasName) {
999 | if (!hasName) {
1000 | return false;
1001 | }
1002 |
1003 | const name = getName();
1004 | this.setFirstName(name);
1005 |
1006 | return true;
1007 | }
1008 | ```
1009 |
1010 | **[⬆ back to top](#table-of-contents)**
1011 |
1012 |
1013 | ## Hoisting
1014 |
1015 | - [14.1](#14.1) `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).
1016 |
1017 | ```javascript
1018 | // we know this wouldn't work (assuming there
1019 | // is no notDefined global variable)
1020 | function example() {
1021 | console.log(notDefined); // => throws a ReferenceError
1022 | }
1023 |
1024 | // creating a variable declaration after you
1025 | // reference the variable will work due to
1026 | // variable hoisting. Note: the assignment
1027 | // value of `true` is not hoisted.
1028 | function example() {
1029 | console.log(declaredButNotAssigned); // => undefined
1030 | var declaredButNotAssigned = true;
1031 | }
1032 |
1033 | // The interpreter is hoisting the variable
1034 | // declaration to the top of the scope,
1035 | // which means our example could be rewritten as:
1036 | function example() {
1037 | let declaredButNotAssigned;
1038 | console.log(declaredButNotAssigned); // => undefined
1039 | declaredButNotAssigned = true;
1040 | }
1041 |
1042 | // using const and let
1043 | function example() {
1044 | console.log(declaredButNotAssigned); // => throws a ReferenceError
1045 | console.log(typeof declaredButNotAssigned); // => throws a ReferenceError
1046 | const declaredButNotAssigned = true;
1047 | }
1048 | ```
1049 |
1050 | - [14.2](#14.2) Anonymous function expressions hoist their variable name, but not the function assignment.
1051 |
1052 | ```javascript
1053 | function example() {
1054 | console.log(anonymous); // => undefined
1055 |
1056 | anonymous(); // => TypeError anonymous is not a function
1057 |
1058 | var anonymous = function() {
1059 | console.log('anonymous function expression');
1060 | };
1061 | }
1062 | ```
1063 |
1064 | - [14.3](#14.3) Named function expressions hoist the variable name, not the function name or the function body.
1065 |
1066 | ```javascript
1067 | function example() {
1068 | console.log(named); // => undefined
1069 |
1070 | named(); // => TypeError named is not a function
1071 |
1072 | superPower(); // => ReferenceError superPower is not defined
1073 |
1074 | var named = function superPower() {
1075 | console.log('Flying');
1076 | };
1077 | }
1078 |
1079 | // the same is true when the function name
1080 | // is the same as the variable name.
1081 | function example() {
1082 | console.log(named); // => undefined
1083 |
1084 | named(); // => TypeError named is not a function
1085 |
1086 | var named = function named() {
1087 | console.log('named');
1088 | }
1089 | }
1090 | ```
1091 |
1092 | - [14.4](#14.4) Function declarations hoist their name and the function body.
1093 |
1094 | ```javascript
1095 | function example() {
1096 | superPower(); // => Flying
1097 |
1098 | function superPower() {
1099 | console.log('Flying');
1100 | }
1101 | }
1102 | ```
1103 |
1104 | - 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/).
1105 |
1106 | **[⬆ back to top](#table-of-contents)**
1107 |
1108 |
1109 | ## Comparison Operators & Equality
1110 |
1111 | - [15.1](#15.1) Use `===` and `!==` over `==` and `!=`.
1112 | - [15.2](#15.2) Conditional statements such as the `if` statement evaluate their expression using coercion with the `ToBoolean` abstract method and always follow these simple rules:
1113 |
1114 | + **Objects** evaluate to **true**
1115 | + **Undefined** evaluates to **false**
1116 | + **Null** evaluates to **false**
1117 | + **Booleans** evaluate to **the value of the boolean**
1118 | + **Numbers** evaluate to **false** if **+0, -0, or NaN**, otherwise **true**
1119 | + **Strings** evaluate to **false** if an empty string `''`, otherwise **true**
1120 |
1121 | ```javascript
1122 | if ([0]) {
1123 | // true
1124 | // An array is an object, objects evaluate to true
1125 | }
1126 | ```
1127 |
1128 | - [15.3](#15.3) Use shortcuts.
1129 |
1130 | ```javascript
1131 | // bad
1132 | if (name !== '') {
1133 | // ...stuff...
1134 | }
1135 |
1136 | // good
1137 | if (name) {
1138 | // ...stuff...
1139 | }
1140 |
1141 | // bad
1142 | if (collection.length > 0) {
1143 | // ...stuff...
1144 | }
1145 |
1146 | // good
1147 | if (collection.length) {
1148 | // ...stuff...
1149 | }
1150 | ```
1151 |
1152 | - [15.4](#15.4) For more information see [Truth Equality and JavaScript](http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) by Angus Croll.
1153 |
1154 | **[⬆ back to top](#table-of-contents)**
1155 |
1156 |
1157 | ## Blocks
1158 |
1159 | - [16.1](#16.1) Use braces with all multi-line blocks.
1160 |
1161 | ```javascript
1162 | // bad
1163 | if (test)
1164 | return false;
1165 |
1166 | // good
1167 | if (test) return false;
1168 |
1169 | // good
1170 | if (test) {
1171 | return false;
1172 | }
1173 |
1174 | // bad
1175 | function() { return false; }
1176 |
1177 | // good
1178 | function() {
1179 | return false;
1180 | }
1181 | ```
1182 |
1183 | - [16.2](#16.2) If you're using multi-line blocks with `if` and `else`, put `else` on the same line as your
1184 | `if` block's closing brace.
1185 |
1186 | ```javascript
1187 | // bad
1188 | if (test) {
1189 | thing1();
1190 | thing2();
1191 | }
1192 | else {
1193 | thing3();
1194 | }
1195 |
1196 | // good
1197 | if (test) {
1198 | thing1();
1199 | thing2();
1200 | } else {
1201 | thing3();
1202 | }
1203 | ```
1204 |
1205 |
1206 | **[⬆ back to top](#table-of-contents)**
1207 |
1208 |
1209 | ## Comments
1210 |
1211 | - [17.1](#17.1) Use `/** ... */` for multi-line comments. Include a description, specify types and values for all parameters and return values.
1212 |
1213 | ```javascript
1214 | // bad
1215 | // make() returns a new element
1216 | // based on the passed in tag name
1217 | //
1218 | // @param {String} tag
1219 | // @return {Element} element
1220 | function make(tag) {
1221 |
1222 | // ...stuff...
1223 |
1224 | return element;
1225 | }
1226 |
1227 | // good
1228 | /**
1229 | * make() returns a new element
1230 | * based on the passed in tag name
1231 | *
1232 | * @param {String} tag
1233 | * @return {Element} element
1234 | */
1235 | function make(tag) {
1236 |
1237 | // ...stuff...
1238 |
1239 | return element;
1240 | }
1241 | ```
1242 |
1243 | - [17.2](#17.2) Use `//` for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment.
1244 |
1245 | ```javascript
1246 | // bad
1247 | const active = true; // is current tab
1248 |
1249 | // good
1250 | // is current tab
1251 | const active = true;
1252 |
1253 | // bad
1254 | function getType() {
1255 | console.log('fetching type...');
1256 | // set the default type to 'no type'
1257 | const type = this._type || 'no type';
1258 |
1259 | return type;
1260 | }
1261 |
1262 | // good
1263 | function getType() {
1264 | console.log('fetching type...');
1265 |
1266 | // set the default type to 'no type'
1267 | const type = this._type || 'no type';
1268 |
1269 | return type;
1270 | }
1271 | ```
1272 |
1273 | - [17.3](#17.3) Prefixing your comments with `FIXME` or `TODO` helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are `FIXME -- need to figure this out` or `TODO -- need to implement`.
1274 |
1275 | - [17.4](#17.4) Use `// FIXME:` to annotate problems.
1276 |
1277 | ```javascript
1278 | class Calculator extends Abacus {
1279 | constructor() {
1280 | super();
1281 |
1282 | // FIXME: shouldn't use a global here
1283 | total = 0;
1284 | }
1285 | }
1286 | ```
1287 |
1288 | - [17.5](#17.5) Use `// TODO:` to annotate solutions to problems.
1289 |
1290 | ```javascript
1291 | class Calculator extends Abacus {
1292 | constructor() {
1293 | super();
1294 |
1295 | // TODO: total should be configurable by an options param
1296 | this.total = 0;
1297 | }
1298 | }
1299 | ```
1300 |
1301 | **[⬆ back to top](#table-of-contents)**
1302 |
1303 |
1304 | ## Whitespace
1305 |
1306 | - [18.1](#18.1) Use soft tabs set to 2 spaces.
1307 |
1308 | ```javascript
1309 | // bad
1310 | function() {
1311 | ∙∙∙∙const name;
1312 | }
1313 |
1314 | // bad
1315 | function() {
1316 | ∙const name;
1317 | }
1318 |
1319 | // good
1320 | function() {
1321 | ∙∙const name;
1322 | }
1323 | ```
1324 |
1325 | - [18.2](#18.2) Place 1 space before the leading brace.
1326 |
1327 | ```javascript
1328 | // bad
1329 | function test(){
1330 | console.log('test');
1331 | }
1332 |
1333 | // good
1334 | function test() {
1335 | console.log('test');
1336 | }
1337 |
1338 | // bad
1339 | dog.set('attr',{
1340 | age: '1 year',
1341 | breed: 'Bernese Mountain Dog',
1342 | });
1343 |
1344 | // good
1345 | dog.set('attr', {
1346 | age: '1 year',
1347 | breed: 'Bernese Mountain Dog',
1348 | });
1349 | ```
1350 |
1351 | - [18.3](#18.3) Place 1 space before the opening parenthesis in control statements (`if`, `while` etc.). Place no space before the argument list in function calls and declarations.
1352 |
1353 | ```javascript
1354 | // bad
1355 | if(isJedi) {
1356 | fight ();
1357 | }
1358 |
1359 | // good
1360 | if (isJedi) {
1361 | fight();
1362 | }
1363 |
1364 | // bad
1365 | function fight () {
1366 | console.log ('Swooosh!');
1367 | }
1368 |
1369 | // good
1370 | function fight() {
1371 | console.log('Swooosh!');
1372 | }
1373 | ```
1374 |
1375 | - [18.4](#18.4) Set off operators with spaces.
1376 |
1377 | ```javascript
1378 | // bad
1379 | const x=y+5;
1380 |
1381 | // good
1382 | const x = y + 5;
1383 | ```
1384 |
1385 | - [18.5](#18.5) End files with a single newline character.
1386 |
1387 | ```javascript
1388 | // bad
1389 | (function(global) {
1390 | // ...stuff...
1391 | })(this);
1392 | ```
1393 |
1394 | ```javascript
1395 | // bad
1396 | (function(global) {
1397 | // ...stuff...
1398 | })(this);↵
1399 | ↵
1400 | ```
1401 |
1402 | ```javascript
1403 | // good
1404 | (function(global) {
1405 | // ...stuff...
1406 | })(this);↵
1407 | ```
1408 |
1409 | - [18.6](#18.6) Use indentation when making long method chains. Use a leading dot, which
1410 | emphasizes that the line is a method call, not a new statement.
1411 |
1412 | ```javascript
1413 | // bad
1414 | $('#items').find('.selected').highlight().end().find('.open').updateCount();
1415 |
1416 | // bad
1417 | $('#items').
1418 | find('.selected').
1419 | highlight().
1420 | end().
1421 | find('.open').
1422 | updateCount();
1423 |
1424 | // good
1425 | $('#items')
1426 | .find('.selected')
1427 | .highlight()
1428 | .end()
1429 | .find('.open')
1430 | .updateCount();
1431 |
1432 | // bad
1433 | const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').class('led', true)
1434 | .attr('width', (radius + margin) * 2).append('svg:g')
1435 | .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
1436 | .call(tron.led);
1437 |
1438 | // good
1439 | const leds = stage.selectAll('.led')
1440 | .data(data)
1441 | .enter().append('svg:svg')
1442 | .classed('led', true)
1443 | .attr('width', (radius + margin) * 2)
1444 | .append('svg:g')
1445 | .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
1446 | .call(tron.led);
1447 | ```
1448 |
1449 | - [18.7](#18.7) Leave a blank line after blocks and before the next statement.
1450 |
1451 | ```javascript
1452 | // bad
1453 | if (foo) {
1454 | return bar;
1455 | }
1456 | return baz;
1457 |
1458 | // good
1459 | if (foo) {
1460 | return bar;
1461 | }
1462 |
1463 | return baz;
1464 |
1465 | // bad
1466 | const obj = {
1467 | foo() {
1468 | },
1469 | bar() {
1470 | },
1471 | };
1472 | return obj;
1473 |
1474 | // good
1475 | const obj = {
1476 | foo() {
1477 | },
1478 |
1479 | bar() {
1480 | },
1481 | };
1482 |
1483 | return obj;
1484 |
1485 | // bad
1486 | const arr = [
1487 | function foo() {
1488 | },
1489 | function bar() {
1490 | },
1491 | ];
1492 | return arr;
1493 |
1494 | // good
1495 | const arr = [
1496 | function foo() {
1497 | },
1498 |
1499 | function bar() {
1500 | },
1501 | ];
1502 |
1503 | return arr;
1504 | ```
1505 |
1506 |
1507 | **[⬆ back to top](#table-of-contents)**
1508 |
1509 | ## Commas
1510 |
1511 | - [19.1](#19.1) Leading commas: **Nope.**
1512 |
1513 | ```javascript
1514 | // bad
1515 | const story = [
1516 | once
1517 | , upon
1518 | , aTime
1519 | ];
1520 |
1521 | // good
1522 | const story = [
1523 | once,
1524 | upon,
1525 | aTime,
1526 | ];
1527 |
1528 | // bad
1529 | const hero = {
1530 | firstName: 'Ada'
1531 | , lastName: 'Lovelace'
1532 | , birthYear: 1815
1533 | , superPower: 'computers'
1534 | };
1535 |
1536 | // good
1537 | const hero = {
1538 | firstName: 'Ada',
1539 | lastName: 'Lovelace',
1540 | birthYear: 1815,
1541 | superPower: 'computers',
1542 | };
1543 | ```
1544 |
1545 | - [19.2](#19.2) Additional trailing comma: **Yup.**
1546 |
1547 | > 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.
1548 |
1549 | ```javascript
1550 | // bad - git diff without trailing comma
1551 | const hero = {
1552 | firstName: 'Florence',
1553 | - lastName: 'Nightingale'
1554 | + lastName: 'Nightingale',
1555 | + inventorOf: ['coxcomb graph', 'modern nursing']
1556 | }
1557 |
1558 | // good - git diff with trailing comma
1559 | const hero = {
1560 | firstName: 'Florence',
1561 | lastName: 'Nightingale',
1562 | + inventorOf: ['coxcomb chart', 'modern nursing'],
1563 | }
1564 |
1565 | // bad
1566 | const hero = {
1567 | firstName: 'Dana',
1568 | lastName: 'Scully'
1569 | };
1570 |
1571 | const heroes = [
1572 | 'Batman',
1573 | 'Superman'
1574 | ];
1575 |
1576 | // good
1577 | const hero = {
1578 | firstName: 'Dana',
1579 | lastName: 'Scully',
1580 | };
1581 |
1582 | const heroes = [
1583 | 'Batman',
1584 | 'Superman',
1585 | ];
1586 | ```
1587 |
1588 | **[⬆ back to top](#table-of-contents)**
1589 |
1590 |
1591 | ## Semicolons
1592 |
1593 | - [20.1](#20.1) **Yup.**
1594 |
1595 | ```javascript
1596 | // bad
1597 | (function() {
1598 | const name = 'Skywalker'
1599 | return name
1600 | })()
1601 |
1602 | // good
1603 | (() => {
1604 | const name = 'Skywalker';
1605 | return name;
1606 | })();
1607 |
1608 | // good (guards against the function becoming an argument when two files with IIFEs are concatenated)
1609 | ;(() => {
1610 | const name = 'Skywalker';
1611 | return name;
1612 | })();
1613 | ```
1614 |
1615 | [Read more](http://stackoverflow.com/a/7365214/1712802).
1616 |
1617 | **[⬆ back to top](#table-of-contents)**
1618 |
1619 |
1620 | ## Type Casting & Coercion
1621 |
1622 | - [21.1](#21.1) Perform type coercion at the beginning of the statement.
1623 | - [21.2](#21.2) Strings:
1624 |
1625 | ```javascript
1626 | // => this.reviewScore = 9;
1627 |
1628 | // bad
1629 | const totalScore = this.reviewScore + '';
1630 |
1631 | // good
1632 | const totalScore = String(this.reviewScore);
1633 | ```
1634 |
1635 | - [21.3](#21.3) Use `parseInt` for Numbers and always with a radix for type casting.
1636 |
1637 | ```javascript
1638 | const inputValue = '4';
1639 |
1640 | // bad
1641 | const val = new Number(inputValue);
1642 |
1643 | // bad
1644 | const val = +inputValue;
1645 |
1646 | // bad
1647 | const val = inputValue >> 0;
1648 |
1649 | // bad
1650 | const val = parseInt(inputValue);
1651 |
1652 | // good
1653 | const val = Number(inputValue);
1654 |
1655 | // good
1656 | const val = parseInt(inputValue, 10);
1657 | ```
1658 |
1659 | - [21.4](#21.4) 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.
1660 |
1661 | ```javascript
1662 | // good
1663 | /**
1664 | * parseInt was the reason my code was slow.
1665 | * Bitshifting the String to coerce it to a
1666 | * Number made it a lot faster.
1667 | */
1668 | const val = inputValue >> 0;
1669 | ```
1670 |
1671 | - [21.5](#21.5) **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:
1672 |
1673 | ```javascript
1674 | 2147483647 >> 0 //=> 2147483647
1675 | 2147483648 >> 0 //=> -2147483648
1676 | 2147483649 >> 0 //=> -2147483647
1677 | ```
1678 |
1679 | - [21.6](#21.6) Booleans:
1680 |
1681 | ```javascript
1682 | const age = 0;
1683 |
1684 | // bad
1685 | const hasAge = new Boolean(age);
1686 |
1687 | // good
1688 | const hasAge = Boolean(age);
1689 |
1690 | // good
1691 | const hasAge = !!age;
1692 | ```
1693 |
1694 | **[⬆ back to top](#table-of-contents)**
1695 |
1696 |
1697 | ## Naming Conventions
1698 |
1699 | - [22.1](#22.1) Avoid single letter names. Be descriptive with your naming.
1700 |
1701 | ```javascript
1702 | // bad
1703 | function q() {
1704 | // ...stuff...
1705 | }
1706 |
1707 | // good
1708 | function query() {
1709 | // ..stuff..
1710 | }
1711 | ```
1712 |
1713 | - [22.2](#22.2) Use camelCase when naming objects, functions, and instances.
1714 |
1715 | ```javascript
1716 | // bad
1717 | const OBJEcttsssss = {};
1718 | const this_is_my_object = {};
1719 | function c() {}
1720 |
1721 | // good
1722 | const thisIsMyObject = {};
1723 | function thisIsMyFunction() {}
1724 | ```
1725 |
1726 | - [22.3](#22.3) Use PascalCase when naming constructors or classes.
1727 |
1728 | ```javascript
1729 | // bad
1730 | function user(options) {
1731 | this.name = options.name;
1732 | }
1733 |
1734 | const bad = new user({
1735 | name: 'nope',
1736 | });
1737 |
1738 | // good
1739 | class User {
1740 | constructor(options) {
1741 | this.name = options.name;
1742 | }
1743 | }
1744 |
1745 | const good = new User({
1746 | name: 'yup',
1747 | });
1748 | ```
1749 |
1750 | - [22.4](#22.4) Use a leading underscore `_` when naming private properties.
1751 |
1752 | ```javascript
1753 | // bad
1754 | this.__firstName__ = 'Panda';
1755 | this.firstName_ = 'Panda';
1756 |
1757 | // good
1758 | this._firstName = 'Panda';
1759 | ```
1760 |
1761 | - [22.5](#22.5) Don't save references to `this`. Use arrow functions or Function#bind.
1762 |
1763 | ```javascript
1764 | // bad
1765 | function foo() {
1766 | const self = this;
1767 | return function() {
1768 | console.log(self);
1769 | };
1770 | }
1771 |
1772 | // bad
1773 | function foo() {
1774 | const that = this;
1775 | return function() {
1776 | console.log(that);
1777 | };
1778 | }
1779 |
1780 | // good
1781 | function foo() {
1782 | return () => {
1783 | console.log(this);
1784 | };
1785 | }
1786 | ```
1787 |
1788 | - [22.6](#22.6) If your file exports a single class, your filename should be exactly the name of the class.
1789 | ```javascript
1790 | // file contents
1791 | class CheckBox {
1792 | // ...
1793 | }
1794 | export default CheckBox;
1795 |
1796 | // in some other file
1797 | // bad
1798 | import CheckBox from './checkBox';
1799 |
1800 | // bad
1801 | import CheckBox from './check_box';
1802 |
1803 | // good
1804 | import CheckBox from './CheckBox';
1805 | ```
1806 |
1807 | - [22.7](#22.7) Use camelCase when you export-default a function. Your filename should be identical to your function's name.
1808 |
1809 | ```javascript
1810 | function makeStyleGuide() {
1811 | }
1812 |
1813 | export default makeStyleGuide;
1814 | ```
1815 |
1816 | - [22.8](#22.8) Use PascalCase when you export a singleton / function library / bare object.
1817 |
1818 | ```javascript
1819 | const AirbnbStyleGuide = {
1820 | es6: {
1821 | }
1822 | };
1823 |
1824 | export default AirbnbStyleGuide;
1825 | ```
1826 |
1827 |
1828 | **[⬆ back to top](#table-of-contents)**
1829 |
1830 |
1831 | ## Accessors
1832 |
1833 | - [23.1](#23.1) Accessor functions for properties are not required.
1834 | - [23.2](#23.2) If you do make accessor functions use getVal() and setVal('hello').
1835 |
1836 | ```javascript
1837 | // bad
1838 | dragon.age();
1839 |
1840 | // good
1841 | dragon.getAge();
1842 |
1843 | // bad
1844 | dragon.age(25);
1845 |
1846 | // good
1847 | dragon.setAge(25);
1848 | ```
1849 |
1850 | - [23.3](#23.3) If the property is a `boolean`, use `isVal()` or `hasVal()`.
1851 |
1852 | ```javascript
1853 | // bad
1854 | if (!dragon.age()) {
1855 | return false;
1856 | }
1857 |
1858 | // good
1859 | if (!dragon.hasAge()) {
1860 | return false;
1861 | }
1862 | ```
1863 |
1864 | - [23.4](#23.4) It's okay to create get() and set() functions, but be consistent.
1865 |
1866 | ```javascript
1867 | class Jedi {
1868 | constructor(options = {}) {
1869 | const lightsaber = options.lightsaber || 'blue';
1870 | this.set('lightsaber', lightsaber);
1871 | }
1872 |
1873 | set(key, val) {
1874 | this[key] = val;
1875 | }
1876 |
1877 | get(key) {
1878 | return this[key];
1879 | }
1880 | }
1881 | ```
1882 |
1883 | **[⬆ back to top](#table-of-contents)**
1884 |
1885 |
1886 | ## Events
1887 |
1888 | - [24.1](#24.1) 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:
1889 |
1890 | ```javascript
1891 | // bad
1892 | $(this).trigger('listingUpdated', listing.id);
1893 |
1894 | ...
1895 |
1896 | $(this).on('listingUpdated', function(e, listingId) {
1897 | // do something with listingId
1898 | });
1899 | ```
1900 |
1901 | prefer:
1902 |
1903 | ```javascript
1904 | // good
1905 | $(this).trigger('listingUpdated', { listingId: listing.id });
1906 |
1907 | ...
1908 |
1909 | $(this).on('listingUpdated', function(e, data) {
1910 | // do something with data.listingId
1911 | });
1912 | ```
1913 |
1914 | **[⬆ back to top](#table-of-contents)**
1915 |
1916 |
1917 | ## jQuery
1918 |
1919 | - [25.1](#25.1) Prefix jQuery object variables with a `$`.
1920 |
1921 | ```javascript
1922 | // bad
1923 | const sidebar = $('.sidebar');
1924 |
1925 | // good
1926 | const $sidebar = $('.sidebar');
1927 |
1928 | // good
1929 | const $sidebarBtn = $('.sidebar-btn');
1930 | ```
1931 |
1932 | - [25.2](#25.2) Cache jQuery lookups.
1933 |
1934 | ```javascript
1935 | // bad
1936 | function setSidebar() {
1937 | $('.sidebar').hide();
1938 |
1939 | // ...stuff...
1940 |
1941 | $('.sidebar').css({
1942 | 'background-color': 'pink'
1943 | });
1944 | }
1945 |
1946 | // good
1947 | function setSidebar() {
1948 | const $sidebar = $('.sidebar');
1949 | $sidebar.hide();
1950 |
1951 | // ...stuff...
1952 |
1953 | $sidebar.css({
1954 | 'background-color': 'pink'
1955 | });
1956 | }
1957 | ```
1958 |
1959 | - [25.3](#25.3) For DOM queries use Cascading `$('.sidebar ul')` or parent > child `$('.sidebar > ul')`. [jsPerf](http://jsperf.com/jquery-find-vs-context-sel/16)
1960 | - [25.4](#25.4) Use `find` with scoped jQuery object queries.
1961 |
1962 | ```javascript
1963 | // bad
1964 | $('ul', '.sidebar').hide();
1965 |
1966 | // bad
1967 | $('.sidebar').find('ul').hide();
1968 |
1969 | // good
1970 | $('.sidebar ul').hide();
1971 |
1972 | // good
1973 | $('.sidebar > ul').hide();
1974 |
1975 | // good
1976 | $sidebar.find('ul').hide();
1977 | ```
1978 |
1979 | **[⬆ back to top](#table-of-contents)**
1980 |
1981 |
1982 | ## ECMAScript 5 Compatibility
1983 |
1984 | - [26.1](#26.1) Refer to [Kangax](https://twitter.com/kangax/)'s ES5 [compatibility table](http://kangax.github.com/es5-compat-table/).
1985 |
1986 | **[⬆ back to top](#table-of-contents)**
1987 |
1988 | ## ECMAScript 6 Styles
1989 |
1990 | - [27.1](#27.1) This is a collection of links to the various es6 features.
1991 |
1992 | 1. [Arrow Functions](#arrow-functions)
1993 | 1. [Classes](#constructors)
1994 | 1. [Object Shorthand](#es6-object-shorthand)
1995 | 1. [Object Concise](#es6-object-concise)
1996 | 1. [Object Computed Properties](#es6-computed-properties)
1997 | 1. [Template Strings](#es6-template-literals)
1998 | 1. [Destructuring](#destructuring)
1999 | 1. [Default Parameters](#es6-default-parameters)
2000 | 1. [Rest](#es6-rest)
2001 | 1. [Array Spreads](#es6-array-spreads)
2002 | 1. [Let and Const](#references)
2003 | 1. [Iterators and Generators](#iterators-and-generators)
2004 | 1. [Modules](#modules)
2005 |
2006 | **[⬆ back to top](#table-of-contents)**
2007 |
2008 | ## Testing
2009 |
2010 | - [28.1](#28.1) **Yup.**
2011 |
2012 | ```javascript
2013 | function() {
2014 | return true;
2015 | }
2016 | ```
2017 |
2018 | **[⬆ back to top](#table-of-contents)**
2019 |
2020 |
2021 | ## Performance
2022 |
2023 | - [On Layout & Web Performance](http://kellegous.com/j/2013/01/26/layout-performance/)
2024 | - [String vs Array Concat](http://jsperf.com/string-vs-array-concat/2)
2025 | - [Try/Catch Cost In a Loop](http://jsperf.com/try-catch-in-loop-cost)
2026 | - [Bang Function](http://jsperf.com/bang-function)
2027 | - [jQuery Find vs Context, Selector](http://jsperf.com/jquery-find-vs-context-sel/13)
2028 | - [innerHTML vs textContent for script text](http://jsperf.com/innerhtml-vs-textcontent-for-script-text)
2029 | - [Long String Concatenation](http://jsperf.com/ya-string-concat)
2030 | - Loading...
2031 |
2032 | **[⬆ back to top](#table-of-contents)**
2033 |
2034 |
2035 | ## Resources
2036 |
2037 | **Learning ES6**
2038 |
2039 | - [Draft ECMA 2015 (ES6) Spec](https://people.mozilla.org/~jorendorff/es6-draft.html)
2040 | - [ExploringJS](http://exploringjs.com/)
2041 | - [ES6 Compatibility Table](https://kangax.github.io/compat-table/es6/)
2042 | - [Comprehensive Overview of ES6 Features](http://es6-features.org/)
2043 |
2044 | **Read This**
2045 |
2046 | - [Standard ECMA-262](http://www.ecma-international.org/ecma-262/6.0/index.html)
2047 |
2048 | **Tools**
2049 |
2050 | - Code Style Linters
2051 | + [ESlint](http://eslint.org/) - [Airbnb Style .eslintrc](https://github.com/airbnb/javascript/blob/master/linters/.eslintrc)
2052 | + [JSHint](http://www.jshint.com/) - [Airbnb Style .jshintrc](https://github.com/airbnb/javascript/blob/master/linters/jshintrc)
2053 | + [JSCS](https://github.com/jscs-dev/node-jscs) - [Airbnb Style Preset](https://github.com/jscs-dev/node-jscs/blob/master/presets/airbnb.json)
2054 |
2055 | **Other Style Guides**
2056 |
2057 | - [Google JavaScript Style Guide](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml)
2058 | - [jQuery Core Style Guidelines](http://docs.jquery.com/JQuery_Core_Style_Guidelines)
2059 | - [Principles of Writing Consistent, Idiomatic JavaScript](https://github.com/rwldrn/idiomatic.js/)
2060 |
2061 | **Other Styles**
2062 |
2063 | - [Naming this in nested functions](https://gist.github.com/4135065) - Christian Johansen
2064 | - [Conditional Callbacks](https://github.com/airbnb/javascript/issues/52) - Ross Allen
2065 | - [Popular JavaScript Coding Conventions on Github](http://sideeffect.kr/popularconvention/#javascript) - JeongHoon Byun
2066 | - [Multiple var statements in JavaScript, not superfluous](http://benalman.com/news/2012/05/multiple-var-statements-javascript/) - Ben Alman
2067 |
2068 | **Further Reading**
2069 |
2070 | - [Understanding JavaScript Closures](http://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/) - Angus Croll
2071 | - [Basic JavaScript for the impatient programmer](http://www.2ality.com/2013/06/basic-javascript.html) - Dr. Axel Rauschmayer
2072 | - [You Might Not Need jQuery](http://youmightnotneedjquery.com/) - Zack Bloom & Adam Schwartz
2073 | - [ES6 Features](https://github.com/lukehoban/es6features) - Luke Hoban
2074 | - [Frontend Guidelines](https://github.com/bendc/frontend-guidelines) - Benjamin De Cock
2075 |
2076 | **Books**
2077 |
2078 | - [JavaScript: The Good Parts](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) - Douglas Crockford
2079 | - [JavaScript Patterns](http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752) - Stoyan Stefanov
2080 | - [Pro JavaScript Design Patterns](http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X) - Ross Harmes and Dustin Diaz
2081 | - [High Performance Web Sites: Essential Knowledge for Front-End Engineers](http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309) - Steve Souders
2082 | - [Maintainable JavaScript](http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680) - Nicholas C. Zakas
2083 | - [JavaScript Web Applications](http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X) - Alex MacCaw
2084 | - [Pro JavaScript Techniques](http://www.amazon.com/Pro-JavaScript-Techniques-John-Resig/dp/1590597273) - John Resig
2085 | - [Smashing Node.js: JavaScript Everywhere](http://www.amazon.com/Smashing-Node-js-JavaScript-Everywhere-Magazine/dp/1119962595) - Guillermo Rauch
2086 | - [Secrets of the JavaScript Ninja](http://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/193398869X) - John Resig and Bear Bibeault
2087 | - [Human JavaScript](http://humanjavascript.com/) - Henrik Joreteg
2088 | - [Superhero.js](http://superherojs.com/) - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy
2089 | - [JSBooks](http://jsbooks.revolunet.com/) - Julien Bouquillon
2090 | - [Third Party JavaScript](http://manning.com/vinegar/) - Ben Vinegar and Anton Kovalyov
2091 | - [Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript](http://amzn.com/0321812182) - David Herman
2092 | - [Eloquent JavaScript](http://eloquentjavascript.net/) - Marijn Haverbeke
2093 | - [You Don't Know JS: ES6 & Beyond](http://shop.oreilly.com/product/0636920033769.do) - Kyle Simpson
2094 |
2095 | **Blogs**
2096 |
2097 | - [DailyJS](http://dailyjs.com/)
2098 | - [JavaScript Weekly](http://javascriptweekly.com/)
2099 | - [JavaScript, JavaScript...](http://javascriptweblog.wordpress.com/)
2100 | - [Bocoup Weblog](http://weblog.bocoup.com/)
2101 | - [Adequately Good](http://www.adequatelygood.com/)
2102 | - [NCZOnline](http://www.nczonline.net/)
2103 | - [Perfection Kills](http://perfectionkills.com/)
2104 | - [Ben Alman](http://benalman.com/)
2105 | - [Dmitry Baranovskiy](http://dmitry.baranovskiy.com/)
2106 | - [Dustin Diaz](http://dustindiaz.com/)
2107 | - [nettuts](http://net.tutsplus.com/?s=javascript)
2108 |
2109 | **Podcasts**
2110 |
2111 | - [JavaScript Jabber](http://devchat.tv/js-jabber/)
2112 |
2113 |
2114 | **[⬆ back to top](#table-of-contents)**
2115 |
2116 | ## In the Wild
2117 |
2118 | 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.
2119 |
2120 | - **Aan Zee**: [AanZee/javascript](https://github.com/AanZee/javascript)
2121 | - **Adult Swim**: [adult-swim/javascript](https://github.com/adult-swim/javascript)
2122 | - **Airbnb**: [airbnb/javascript](https://github.com/airbnb/javascript)
2123 | - **Apartmint**: [apartmint/javascript](https://github.com/apartmint/javascript)
2124 | - **Avalara**: [avalara/javascript](https://github.com/avalara/javascript)
2125 | - **Billabong**: [billabong/javascript](https://github.com/billabong/javascript)
2126 | - **Blendle**: [blendle/javascript](https://github.com/blendle/javascript)
2127 | - **ComparaOnline**: [comparaonline/javascript](https://github.com/comparaonline/javascript)
2128 | - **Compass Learning**: [compasslearning/javascript-style-guide](https://github.com/compasslearning/javascript-style-guide)
2129 | - **DailyMotion**: [dailymotion/javascript](https://github.com/dailymotion/javascript)
2130 | - **Digitpaint** [digitpaint/javascript](https://github.com/digitpaint/javascript)
2131 | - **Evernote**: [evernote/javascript-style-guide](https://github.com/evernote/javascript-style-guide)
2132 | - **ExactTarget**: [ExactTarget/javascript](https://github.com/ExactTarget/javascript)
2133 | - **Expensify** [Expensify/Style-Guide](https://github.com/Expensify/Style-Guide/blob/master/javascript.md)
2134 | - **Flexberry**: [Flexberry/javascript-style-guide](https://github.com/Flexberry/javascript-style-guide)
2135 | - **Gawker Media**: [gawkermedia/javascript](https://github.com/gawkermedia/javascript)
2136 | - **General Electric**: [GeneralElectric/javascript](https://github.com/GeneralElectric/javascript)
2137 | - **GoodData**: [gooddata/gdc-js-style](https://github.com/gooddata/gdc-js-style)
2138 | - **Grooveshark**: [grooveshark/javascript](https://github.com/grooveshark/javascript)
2139 | - **How About We**: [howaboutwe/javascript](https://github.com/howaboutwe/javascript)
2140 | - **Huballin**: [huballin/javascript](https://github.com/huballin/javascript)
2141 | - **InfoJobs**: [InfoJobs/JavaScript-Style-Guide](https://github.com/InfoJobs/JavaScript-Style-Guide)
2142 | - **Intent Media**: [intentmedia/javascript](https://github.com/intentmedia/javascript)
2143 | - **Jam3**: [Jam3/Javascript-Code-Conventions](https://github.com/Jam3/Javascript-Code-Conventions)
2144 | - **JSSolutions**: [JSSolutions/javascript](https://github.com/JSSolutions/javascript)
2145 | - **Kinetica Solutions**: [kinetica/javascript](https://github.com/kinetica/javascript)
2146 | - **Mighty Spring**: [mightyspring/javascript](https://github.com/mightyspring/javascript)
2147 | - **MinnPost**: [MinnPost/javascript](https://github.com/MinnPost/javascript)
2148 | - **MitocGroup**: [MitocGroup/javascript](https://github.com/MitocGroup/javascript)
2149 | - **ModCloth**: [modcloth/javascript](https://github.com/modcloth/javascript)
2150 | - **Money Advice Service**: [moneyadviceservice/javascript](https://github.com/moneyadviceservice/javascript)
2151 | - **Muber**: [muber/javascript](https://github.com/muber/javascript)
2152 | - **National Geographic**: [natgeo/javascript](https://github.com/natgeo/javascript)
2153 | - **National Park Service**: [nationalparkservice/javascript](https://github.com/nationalparkservice/javascript)
2154 | - **Nimbl3**: [nimbl3/javascript](https://github.com/nimbl3/javascript)
2155 | - **Orion Health**: [orionhealth/javascript](https://github.com/orionhealth/javascript)
2156 | - **Peerby**: [Peerby/javascript](https://github.com/Peerby/javascript)
2157 | - **Razorfish**: [razorfish/javascript-style-guide](https://github.com/razorfish/javascript-style-guide)
2158 | - **reddit**: [reddit/styleguide/javascript](https://github.com/reddit/styleguide/tree/master/javascript)
2159 | - **REI**: [reidev/js-style-guide](https://github.com/reidev/js-style-guide)
2160 | - **Ripple**: [ripple/javascript-style-guide](https://github.com/ripple/javascript-style-guide)
2161 | - **SeekingAlpha**: [seekingalpha/javascript-style-guide](https://github.com/seekingalpha/javascript-style-guide)
2162 | - **Shutterfly**: [shutterfly/javascript](https://github.com/shutterfly/javascript)
2163 | - **Springload**: [springload/javascript](https://github.com/springload/javascript)
2164 | - **StudentSphere**: [studentsphere/javascript](https://github.com/studentsphere/javascript)
2165 | - **Target**: [target/javascript](https://github.com/target/javascript)
2166 | - **TheLadders**: [TheLadders/javascript](https://github.com/TheLadders/javascript)
2167 | - **T4R Technology**: [T4R-Technology/javascript](https://github.com/T4R-Technology/javascript)
2168 | - **VoxFeed**: [VoxFeed/javascript-style-guide](https://github.com/VoxFeed/javascript-style-guide)
2169 | - **Weggo**: [Weggo/javascript](https://github.com/Weggo/javascript)
2170 | - **Zillow**: [zillow/javascript](https://github.com/zillow/javascript)
2171 | - **ZocDoc**: [ZocDoc/javascript](https://github.com/ZocDoc/javascript)
2172 |
2173 | **[⬆ back to top](#table-of-contents)**
2174 |
2175 | ## Translation
2176 |
2177 | This style guide is also available in other languages:
2178 |
2179 | -  **Brazilian Portuguese**: [armoucar/javascript-style-guide](https://github.com/armoucar/javascript-style-guide)
2180 | -  **Bulgarian**: [borislavvv/javascript](https://github.com/borislavvv/javascript)
2181 | -  **Catalan**: [fpmweb/javascript-style-guide](https://github.com/fpmweb/javascript-style-guide)
2182 | -  **Chinese(Traditional)**: [jigsawye/javascript](https://github.com/jigsawye/javascript)
2183 | -  **Chinese(Simplified)**: [sivan/javascript-style-guide](https://github.com/sivan/javascript-style-guide)
2184 | -  **French**: [nmussy/javascript-style-guide](https://github.com/nmussy/javascript-style-guide)
2185 | -  **German**: [timofurrer/javascript-style-guide](https://github.com/timofurrer/javascript-style-guide)
2186 | -  **Italian**: [sinkswim/javascript-style-guide](https://github.com/sinkswim/javascript-style-guide)
2187 | -  **Japanese**: [mitsuruog/javacript-style-guide](https://github.com/mitsuruog/javacript-style-guide)
2188 | -  **Korean**: [tipjs/javascript-style-guide](https://github.com/tipjs/javascript-style-guide)
2189 | -  **Polish**: [mjurczyk/javascript](https://github.com/mjurczyk/javascript)
2190 | -  **Russian**: [uprock/javascript](https://github.com/uprock/javascript)
2191 | -  **Spanish**: [paolocarrasco/javascript-style-guide](https://github.com/paolocarrasco/javascript-style-guide)
2192 | -  **Thai**: [lvarayut/javascript-style-guide](https://github.com/lvarayut/javascript-style-guide)
2193 |
2194 | ## The JavaScript Style Guide Guide
2195 |
2196 | - [Reference](https://github.com/airbnb/javascript/wiki/The-JavaScript-Style-Guide-Guide)
2197 |
2198 | ## Chat With Us About JavaScript
2199 |
2200 | - Find us on [gitter](https://gitter.im/airbnb/javascript).
2201 |
2202 | ## Contributors
2203 |
2204 | - [View Contributors](https://github.com/airbnb/javascript/graphs/contributors)
2205 |
2206 |
2207 | ## License
2208 |
2209 | (The MIT License)
2210 |
2211 | Copyright (c) 2014 Airbnb
2212 |
2213 | Permission is hereby granted, free of charge, to any person obtaining
2214 | a copy of this software and associated documentation files (the
2215 | 'Software'), to deal in the Software without restriction, including
2216 | without limitation the rights to use, copy, modify, merge, publish,
2217 | distribute, sublicense, and/or sell copies of the Software, and to
2218 | permit persons to whom the Software is furnished to do so, subject to
2219 | the following conditions:
2220 |
2221 | The above copyright notice and this permission notice shall be
2222 | included in all copies or substantial portions of the Software.
2223 |
2224 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
2225 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2226 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
2227 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
2228 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
2229 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
2230 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2231 |
2232 | **[⬆ back to top](#table-of-contents)**
2233 |
2234 | ## Amendments
2235 |
2236 | 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.
2237 |
2238 | # };
2239 |
--------------------------------------------------------------------------------
/es5/README.md:
--------------------------------------------------------------------------------
1 | [](https://gitter.im/airbnb/javascript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
2 |
3 | # Airbnb JavaScript Style Guide() {
4 |
5 | *A mostly reasonable approach to JavaScript*
6 |
7 |
8 | ## Table of Contents
9 |
10 | 1. [Types](#types)
11 | 1. [Objects](#objects)
12 | 1. [Arrays](#arrays)
13 | 1. [Strings](#strings)
14 | 1. [Functions](#functions)
15 | 1. [Properties](#properties)
16 | 1. [Variables](#variables)
17 | 1. [Hoisting](#hoisting)
18 | 1. [Comparison Operators & Equality](#comparison-operators--equality)
19 | 1. [Blocks](#blocks)
20 | 1. [Comments](#comments)
21 | 1. [Whitespace](#whitespace)
22 | 1. [Commas](#commas)
23 | 1. [Semicolons](#semicolons)
24 | 1. [Type Casting & Coercion](#type-casting--coercion)
25 | 1. [Naming Conventions](#naming-conventions)
26 | 1. [Accessors](#accessors)
27 | 1. [Constructors](#constructors)
28 | 1. [Events](#events)
29 | 1. [Modules](#modules)
30 | 1. [jQuery](#jquery)
31 | 1. [ECMAScript 5 Compatibility](#ecmascript-5-compatibility)
32 | 1. [Testing](#testing)
33 | 1. [Performance](#performance)
34 | 1. [Resources](#resources)
35 | 1. [In the Wild](#in-the-wild)
36 | 1. [Translation](#translation)
37 | 1. [The JavaScript Style Guide Guide](#the-javascript-style-guide-guide)
38 | 1. [Chat With Us About Javascript](#chat-with-us-about-javascript)
39 | 1. [Contributors](#contributors)
40 | 1. [License](#license)
41 |
42 | ## Types
43 |
44 | - **Primitives**: When you access a primitive type you work directly on its value.
45 |
46 | + `string`
47 | + `number`
48 | + `boolean`
49 | + `null`
50 | + `undefined`
51 |
52 | ```javascript
53 | var foo = 1;
54 | var bar = foo;
55 |
56 | bar = 9;
57 |
58 | console.log(foo, bar); // => 1, 9
59 | ```
60 | - **Complex**: When you access a complex type you work on a reference to its value.
61 |
62 | + `object`
63 | + `array`
64 | + `function`
65 |
66 | ```javascript
67 | var foo = [1, 2];
68 | var bar = foo;
69 |
70 | bar[0] = 9;
71 |
72 | console.log(foo[0], bar[0]); // => 9, 9
73 | ```
74 |
75 | **[⬆ back to top](#table-of-contents)**
76 |
77 | ## Objects
78 |
79 | - Use the literal syntax for object creation.
80 |
81 | ```javascript
82 | // bad
83 | var item = new Object();
84 |
85 | // good
86 | var item = {};
87 | ```
88 |
89 | - 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).
90 |
91 | ```javascript
92 | // bad
93 | var superman = {
94 | default: { clark: 'kent' },
95 | private: true
96 | };
97 |
98 | // good
99 | var superman = {
100 | defaults: { clark: 'kent' },
101 | hidden: true
102 | };
103 | ```
104 |
105 | - Use readable synonyms in place of reserved words.
106 |
107 | ```javascript
108 | // bad
109 | var superman = {
110 | class: 'alien'
111 | };
112 |
113 | // bad
114 | var superman = {
115 | klass: 'alien'
116 | };
117 |
118 | // good
119 | var superman = {
120 | type: 'alien'
121 | };
122 | ```
123 |
124 | **[⬆ back to top](#table-of-contents)**
125 |
126 | ## Arrays
127 |
128 | - Use the literal syntax for array creation.
129 |
130 | ```javascript
131 | // bad
132 | var items = new Array();
133 |
134 | // good
135 | var items = [];
136 | ```
137 |
138 | - Use Array#push instead of direct assignment to add items to an array.
139 |
140 | ```javascript
141 | var someStack = [];
142 |
143 |
144 | // bad
145 | someStack[someStack.length] = 'abracadabra';
146 |
147 | // good
148 | someStack.push('abracadabra');
149 | ```
150 |
151 | - When you need to copy an array use Array#slice. [jsPerf](http://jsperf.com/converting-arguments-to-an-array/7)
152 |
153 | ```javascript
154 | var len = items.length;
155 | var itemsCopy = [];
156 | var i;
157 |
158 | // bad
159 | for (i = 0; i < len; i++) {
160 | itemsCopy[i] = items[i];
161 | }
162 |
163 | // good
164 | itemsCopy = items.slice();
165 | ```
166 |
167 | - To convert an array-like object to an array, use Array#slice.
168 |
169 | ```javascript
170 | function trigger() {
171 | var args = Array.prototype.slice.call(arguments);
172 | ...
173 | }
174 | ```
175 |
176 | **[⬆ back to top](#table-of-contents)**
177 |
178 |
179 | ## Strings
180 |
181 | - Use single quotes `''` for strings.
182 |
183 | ```javascript
184 | // bad
185 | var name = "Bob Parr";
186 |
187 | // good
188 | var name = 'Bob Parr';
189 |
190 | // bad
191 | var fullName = "Bob " + this.lastName;
192 |
193 | // good
194 | var fullName = 'Bob ' + this.lastName;
195 | ```
196 |
197 | - Strings longer than 100 characters should be written across multiple lines using string concatenation.
198 | - 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).
199 |
200 | ```javascript
201 | // bad
202 | 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.';
203 |
204 | // bad
205 | var errorMessage = 'This is a super long error that was thrown because \
206 | of Batman. When you stop to think about how Batman had anything to do \
207 | with this, you would get nowhere \
208 | fast.';
209 |
210 | // good
211 | var errorMessage = 'This is a super long error that was thrown because ' +
212 | 'of Batman. When you stop to think about how Batman had anything to do ' +
213 | 'with this, you would get nowhere fast.';
214 | ```
215 |
216 | - 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).
217 |
218 | ```javascript
219 | var items;
220 | var messages;
221 | var length;
222 | var i;
223 |
224 | messages = [{
225 | state: 'success',
226 | message: 'This one worked.'
227 | }, {
228 | state: 'success',
229 | message: 'This one worked as well.'
230 | }, {
231 | state: 'error',
232 | message: 'This one did not work.'
233 | }];
234 |
235 | length = messages.length;
236 |
237 | // bad
238 | function inbox(messages) {
239 | items = '
';
240 |
241 | for (i = 0; i < length; i++) {
242 | items += '- ' + messages[i].message + '
';
243 | }
244 |
245 | return items + '
';
246 | }
247 |
248 | // good
249 | function inbox(messages) {
250 | items = [];
251 |
252 | for (i = 0; i < length; i++) {
253 | // use direct assignment in this case because we're micro-optimizing.
254 | items[i] = '' + messages[i].message + '';
255 | }
256 |
257 | return '';
258 | }
259 | ```
260 |
261 | **[⬆ back to top](#table-of-contents)**
262 |
263 |
264 | ## Functions
265 |
266 | - Function expressions:
267 |
268 | ```javascript
269 | // anonymous function expression
270 | var anonymous = function() {
271 | return true;
272 | };
273 |
274 | // named function expression
275 | var named = function named() {
276 | return true;
277 | };
278 |
279 | // immediately-invoked function expression (IIFE)
280 | (function() {
281 | console.log('Welcome to the Internet. Please follow me.');
282 | })();
283 | ```
284 |
285 | - 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.
286 | - **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).
287 |
288 | ```javascript
289 | // bad
290 | if (currentUser) {
291 | function test() {
292 | console.log('Nope.');
293 | }
294 | }
295 |
296 | // good
297 | var test;
298 | if (currentUser) {
299 | test = function test() {
300 | console.log('Yup.');
301 | };
302 | }
303 | ```
304 |
305 | - Never name a parameter `arguments`. This will take precedence over the `arguments` object that is given to every function scope.
306 |
307 | ```javascript
308 | // bad
309 | function nope(name, options, arguments) {
310 | // ...stuff...
311 | }
312 |
313 | // good
314 | function yup(name, options, args) {
315 | // ...stuff...
316 | }
317 | ```
318 |
319 | **[⬆ back to top](#table-of-contents)**
320 |
321 |
322 |
323 | ## Properties
324 |
325 | - Use dot notation when accessing properties.
326 |
327 | ```javascript
328 | var luke = {
329 | jedi: true,
330 | age: 28
331 | };
332 |
333 | // bad
334 | var isJedi = luke['jedi'];
335 |
336 | // good
337 | var isJedi = luke.jedi;
338 | ```
339 |
340 | - Use subscript notation `[]` when accessing properties with a variable.
341 |
342 | ```javascript
343 | var luke = {
344 | jedi: true,
345 | age: 28
346 | };
347 |
348 | function getProp(prop) {
349 | return luke[prop];
350 | }
351 |
352 | var isJedi = getProp('jedi');
353 | ```
354 |
355 | **[⬆ back to top](#table-of-contents)**
356 |
357 |
358 | ## Variables
359 |
360 | - 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.
361 |
362 | ```javascript
363 | // bad
364 | superPower = new SuperPower();
365 |
366 | // good
367 | var superPower = new SuperPower();
368 | ```
369 |
370 | - Use one `var` declaration per variable.
371 | It's easier to add new variable declarations this way, and you never have
372 | to worry about swapping out a `;` for a `,` or introducing punctuation-only
373 | diffs.
374 |
375 | ```javascript
376 | // bad
377 | var items = getItems(),
378 | goSportsTeam = true,
379 | dragonball = 'z';
380 |
381 | // bad
382 | // (compare to above, and try to spot the mistake)
383 | var items = getItems(),
384 | goSportsTeam = true;
385 | dragonball = 'z';
386 |
387 | // good
388 | var items = getItems();
389 | var goSportsTeam = true;
390 | var dragonball = 'z';
391 | ```
392 |
393 | - 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.
394 |
395 | ```javascript
396 | // bad
397 | var i, len, dragonball,
398 | items = getItems(),
399 | goSportsTeam = true;
400 |
401 | // bad
402 | var i;
403 | var items = getItems();
404 | var dragonball;
405 | var goSportsTeam = true;
406 | var len;
407 |
408 | // good
409 | var items = getItems();
410 | var goSportsTeam = true;
411 | var dragonball;
412 | var length;
413 | var i;
414 | ```
415 |
416 | - Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues.
417 |
418 | ```javascript
419 | // bad
420 | function() {
421 | test();
422 | console.log('doing stuff..');
423 |
424 | //..other stuff..
425 |
426 | var name = getName();
427 |
428 | if (name === 'test') {
429 | return false;
430 | }
431 |
432 | return name;
433 | }
434 |
435 | // good
436 | function() {
437 | var name = getName();
438 |
439 | test();
440 | console.log('doing stuff..');
441 |
442 | //..other stuff..
443 |
444 | if (name === 'test') {
445 | return false;
446 | }
447 |
448 | return name;
449 | }
450 |
451 | // bad - unnecessary function call
452 | function() {
453 | var name = getName();
454 |
455 | if (!arguments.length) {
456 | return false;
457 | }
458 |
459 | this.setFirstName(name);
460 |
461 | return true;
462 | }
463 |
464 | // good
465 | function() {
466 | var name;
467 |
468 | if (!arguments.length) {
469 | return false;
470 | }
471 |
472 | name = getName();
473 | this.setFirstName(name);
474 |
475 | return true;
476 | }
477 | ```
478 |
479 | **[⬆ back to top](#table-of-contents)**
480 |
481 |
482 | ## Hoisting
483 |
484 | - Variable declarations get hoisted to the top of their scope, but their assignment does not.
485 |
486 | ```javascript
487 | // we know this wouldn't work (assuming there
488 | // is no notDefined global variable)
489 | function example() {
490 | console.log(notDefined); // => throws a ReferenceError
491 | }
492 |
493 | // creating a variable declaration after you
494 | // reference the variable will work due to
495 | // variable hoisting. Note: the assignment
496 | // value of `true` is not hoisted.
497 | function example() {
498 | console.log(declaredButNotAssigned); // => undefined
499 | var declaredButNotAssigned = true;
500 | }
501 |
502 | // The interpreter is hoisting the variable
503 | // declaration to the top of the scope,
504 | // which means our example could be rewritten as:
505 | function example() {
506 | var declaredButNotAssigned;
507 | console.log(declaredButNotAssigned); // => undefined
508 | declaredButNotAssigned = true;
509 | }
510 | ```
511 |
512 | - Anonymous function expressions hoist their variable name, but not the function assignment.
513 |
514 | ```javascript
515 | function example() {
516 | console.log(anonymous); // => undefined
517 |
518 | anonymous(); // => TypeError anonymous is not a function
519 |
520 | var anonymous = function() {
521 | console.log('anonymous function expression');
522 | };
523 | }
524 | ```
525 |
526 | - Named function expressions hoist the variable name, not the function name or the function body.
527 |
528 | ```javascript
529 | function example() {
530 | console.log(named); // => undefined
531 |
532 | named(); // => TypeError named is not a function
533 |
534 | superPower(); // => ReferenceError superPower is not defined
535 |
536 | var named = function superPower() {
537 | console.log('Flying');
538 | };
539 | }
540 |
541 | // the same is true when the function name
542 | // is the same as the variable name.
543 | function example() {
544 | console.log(named); // => undefined
545 |
546 | named(); // => TypeError named is not a function
547 |
548 | var named = function named() {
549 | console.log('named');
550 | }
551 | }
552 | ```
553 |
554 | - Function declarations hoist their name and the function body.
555 |
556 | ```javascript
557 | function example() {
558 | superPower(); // => Flying
559 |
560 | function superPower() {
561 | console.log('Flying');
562 | }
563 | }
564 | ```
565 |
566 | - 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/).
567 |
568 | **[⬆ back to top](#table-of-contents)**
569 |
570 |
571 |
572 | ## Comparison Operators & Equality
573 |
574 | - Use `===` and `!==` over `==` and `!=`.
575 | - Conditional statements such as the `if` statement evaluate their expression using coercion with the `ToBoolean` abstract method and always follow these simple rules:
576 |
577 | + **Objects** evaluate to **true**
578 | + **Undefined** evaluates to **false**
579 | + **Null** evaluates to **false**
580 | + **Booleans** evaluate to **the value of the boolean**
581 | + **Numbers** evaluate to **false** if **+0, -0, or NaN**, otherwise **true**
582 | + **Strings** evaluate to **false** if an empty string `''`, otherwise **true**
583 |
584 | ```javascript
585 | if ([0]) {
586 | // true
587 | // An array is an object, objects evaluate to true
588 | }
589 | ```
590 |
591 | - Use shortcuts.
592 |
593 | ```javascript
594 | // bad
595 | if (name !== '') {
596 | // ...stuff...
597 | }
598 |
599 | // good
600 | if (name) {
601 | // ...stuff...
602 | }
603 |
604 | // bad
605 | if (collection.length > 0) {
606 | // ...stuff...
607 | }
608 |
609 | // good
610 | if (collection.length) {
611 | // ...stuff...
612 | }
613 | ```
614 |
615 | - For more information see [Truth Equality and JavaScript](http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) by Angus Croll.
616 |
617 | **[⬆ back to top](#table-of-contents)**
618 |
619 |
620 | ## Blocks
621 |
622 | - Use braces with all multi-line blocks.
623 |
624 | ```javascript
625 | // bad
626 | if (test)
627 | return false;
628 |
629 | // good
630 | if (test) return false;
631 |
632 | // good
633 | if (test) {
634 | return false;
635 | }
636 |
637 | // bad
638 | function() { return false; }
639 |
640 | // good
641 | function() {
642 | return false;
643 | }
644 | ```
645 |
646 | - If you're using multi-line blocks with `if` and `else`, put `else` on the same line as your
647 | `if` block's closing brace.
648 |
649 | ```javascript
650 | // bad
651 | if (test) {
652 | thing1();
653 | thing2();
654 | }
655 | else {
656 | thing3();
657 | }
658 |
659 | // good
660 | if (test) {
661 | thing1();
662 | thing2();
663 | } else {
664 | thing3();
665 | }
666 | ```
667 |
668 |
669 | **[⬆ back to top](#table-of-contents)**
670 |
671 |
672 | ## Comments
673 |
674 | - Use `/** ... */` for multi-line comments. Include a description, specify types and values for all parameters and return values.
675 |
676 | ```javascript
677 | // bad
678 | // make() returns a new element
679 | // based on the passed in tag name
680 | //
681 | // @param {String} tag
682 | // @return {Element} element
683 | function make(tag) {
684 |
685 | // ...stuff...
686 |
687 | return element;
688 | }
689 |
690 | // good
691 | /**
692 | * make() returns a new element
693 | * based on the passed in tag name
694 | *
695 | * @param {String} tag
696 | * @return {Element} element
697 | */
698 | function make(tag) {
699 |
700 | // ...stuff...
701 |
702 | return element;
703 | }
704 | ```
705 |
706 | - 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.
707 |
708 | ```javascript
709 | // bad
710 | var active = true; // is current tab
711 |
712 | // good
713 | // is current tab
714 | var active = true;
715 |
716 | // bad
717 | function getType() {
718 | console.log('fetching type...');
719 | // set the default type to 'no type'
720 | var type = this._type || 'no type';
721 |
722 | return type;
723 | }
724 |
725 | // good
726 | function getType() {
727 | console.log('fetching type...');
728 |
729 | // set the default type to 'no type'
730 | var type = this._type || 'no type';
731 |
732 | return type;
733 | }
734 | ```
735 |
736 | - 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`.
737 |
738 | - Use `// FIXME:` to annotate problems.
739 |
740 | ```javascript
741 | function Calculator() {
742 |
743 | // FIXME: shouldn't use a global here
744 | total = 0;
745 |
746 | return this;
747 | }
748 | ```
749 |
750 | - Use `// TODO:` to annotate solutions to problems.
751 |
752 | ```javascript
753 | function Calculator() {
754 |
755 | // TODO: total should be configurable by an options param
756 | this.total = 0;
757 |
758 | return this;
759 | }
760 | ```
761 |
762 | **[⬆ back to top](#table-of-contents)**
763 |
764 |
765 | ## Whitespace
766 |
767 | - Use soft tabs set to 2 spaces.
768 |
769 | ```javascript
770 | // bad
771 | function() {
772 | ∙∙∙∙var name;
773 | }
774 |
775 | // bad
776 | function() {
777 | ∙var name;
778 | }
779 |
780 | // good
781 | function() {
782 | ∙∙var name;
783 | }
784 | ```
785 |
786 | - Place 1 space before the leading brace.
787 |
788 | ```javascript
789 | // bad
790 | function test(){
791 | console.log('test');
792 | }
793 |
794 | // good
795 | function test() {
796 | console.log('test');
797 | }
798 |
799 | // bad
800 | dog.set('attr',{
801 | age: '1 year',
802 | breed: 'Bernese Mountain Dog'
803 | });
804 |
805 | // good
806 | dog.set('attr', {
807 | age: '1 year',
808 | breed: 'Bernese Mountain Dog'
809 | });
810 | ```
811 |
812 | - Place 1 space before the opening parenthesis in control statements (`if`, `while` etc.). Place no space before the argument list in function calls and declarations.
813 |
814 | ```javascript
815 | // bad
816 | if(isJedi) {
817 | fight ();
818 | }
819 |
820 | // good
821 | if (isJedi) {
822 | fight();
823 | }
824 |
825 | // bad
826 | function fight () {
827 | console.log ('Swooosh!');
828 | }
829 |
830 | // good
831 | function fight() {
832 | console.log('Swooosh!');
833 | }
834 | ```
835 |
836 | - Set off operators with spaces.
837 |
838 | ```javascript
839 | // bad
840 | var x=y+5;
841 |
842 | // good
843 | var x = y + 5;
844 | ```
845 |
846 | - End files with a single newline character.
847 |
848 | ```javascript
849 | // bad
850 | (function(global) {
851 | // ...stuff...
852 | })(this);
853 | ```
854 |
855 | ```javascript
856 | // bad
857 | (function(global) {
858 | // ...stuff...
859 | })(this);↵
860 | ↵
861 | ```
862 |
863 | ```javascript
864 | // good
865 | (function(global) {
866 | // ...stuff...
867 | })(this);↵
868 | ```
869 |
870 | - Use indentation when making long method chains. Use a leading dot, which
871 | emphasizes that the line is a method call, not a new statement.
872 |
873 | ```javascript
874 | // bad
875 | $('#items').find('.selected').highlight().end().find('.open').updateCount();
876 |
877 | // bad
878 | $('#items').
879 | find('.selected').
880 | highlight().
881 | end().
882 | find('.open').
883 | updateCount();
884 |
885 | // good
886 | $('#items')
887 | .find('.selected')
888 | .highlight()
889 | .end()
890 | .find('.open')
891 | .updateCount();
892 |
893 | // bad
894 | var leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true)
895 | .attr('width', (radius + margin) * 2).append('svg:g')
896 | .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
897 | .call(tron.led);
898 |
899 | // good
900 | var leds = stage.selectAll('.led')
901 | .data(data)
902 | .enter().append('svg:svg')
903 | .classed('led', true)
904 | .attr('width', (radius + margin) * 2)
905 | .append('svg:g')
906 | .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
907 | .call(tron.led);
908 | ```
909 |
910 | - Leave a blank line after blocks and before the next statement
911 |
912 | ```javascript
913 | // bad
914 | if (foo) {
915 | return bar;
916 | }
917 | return baz;
918 |
919 | // good
920 | if (foo) {
921 | return bar;
922 | }
923 |
924 | return baz;
925 |
926 | // bad
927 | var obj = {
928 | foo: function() {
929 | },
930 | bar: function() {
931 | }
932 | };
933 | return obj;
934 |
935 | // good
936 | var obj = {
937 | foo: function() {
938 | },
939 |
940 | bar: function() {
941 | }
942 | };
943 |
944 | return obj;
945 | ```
946 |
947 |
948 | **[⬆ back to top](#table-of-contents)**
949 |
950 | ## Commas
951 |
952 | - Leading commas: **Nope.**
953 |
954 | ```javascript
955 | // bad
956 | var story = [
957 | once
958 | , upon
959 | , aTime
960 | ];
961 |
962 | // good
963 | var story = [
964 | once,
965 | upon,
966 | aTime
967 | ];
968 |
969 | // bad
970 | var hero = {
971 | firstName: 'Bob'
972 | , lastName: 'Parr'
973 | , heroName: 'Mr. Incredible'
974 | , superPower: 'strength'
975 | };
976 |
977 | // good
978 | var hero = {
979 | firstName: 'Bob',
980 | lastName: 'Parr',
981 | heroName: 'Mr. Incredible',
982 | superPower: 'strength'
983 | };
984 | ```
985 |
986 | - 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)):
987 |
988 | > 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.
989 |
990 | ```javascript
991 | // bad
992 | var hero = {
993 | firstName: 'Kevin',
994 | lastName: 'Flynn',
995 | };
996 |
997 | var heroes = [
998 | 'Batman',
999 | 'Superman',
1000 | ];
1001 |
1002 | // good
1003 | var hero = {
1004 | firstName: 'Kevin',
1005 | lastName: 'Flynn'
1006 | };
1007 |
1008 | var heroes = [
1009 | 'Batman',
1010 | 'Superman'
1011 | ];
1012 | ```
1013 |
1014 | **[⬆ back to top](#table-of-contents)**
1015 |
1016 |
1017 | ## Semicolons
1018 |
1019 | - **Yup.**
1020 |
1021 | ```javascript
1022 | // bad
1023 | (function() {
1024 | var name = 'Skywalker'
1025 | return name
1026 | })()
1027 |
1028 | // good
1029 | (function() {
1030 | var name = 'Skywalker';
1031 | return name;
1032 | })();
1033 |
1034 | // good (guards against the function becoming an argument when two files with IIFEs are concatenated)
1035 | ;(function() {
1036 | var name = 'Skywalker';
1037 | return name;
1038 | })();
1039 | ```
1040 |
1041 | [Read more](http://stackoverflow.com/a/7365214/1712802).
1042 |
1043 | **[⬆ back to top](#table-of-contents)**
1044 |
1045 |
1046 | ## Type Casting & Coercion
1047 |
1048 | - Perform type coercion at the beginning of the statement.
1049 | - Strings:
1050 |
1051 | ```javascript
1052 | // => this.reviewScore = 9;
1053 |
1054 | // bad
1055 | var totalScore = this.reviewScore + '';
1056 |
1057 | // good
1058 | var totalScore = '' + this.reviewScore;
1059 |
1060 | // bad
1061 | var totalScore = '' + this.reviewScore + ' total score';
1062 |
1063 | // good
1064 | var totalScore = this.reviewScore + ' total score';
1065 | ```
1066 |
1067 | - Use `parseInt` for Numbers and always with a radix for type casting.
1068 |
1069 | ```javascript
1070 | var inputValue = '4';
1071 |
1072 | // bad
1073 | var val = new Number(inputValue);
1074 |
1075 | // bad
1076 | var val = +inputValue;
1077 |
1078 | // bad
1079 | var val = inputValue >> 0;
1080 |
1081 | // bad
1082 | var val = parseInt(inputValue);
1083 |
1084 | // good
1085 | var val = Number(inputValue);
1086 |
1087 | // good
1088 | var val = parseInt(inputValue, 10);
1089 | ```
1090 |
1091 | - 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.
1092 |
1093 | ```javascript
1094 | // good
1095 | /**
1096 | * parseInt was the reason my code was slow.
1097 | * Bitshifting the String to coerce it to a
1098 | * Number made it a lot faster.
1099 | */
1100 | var val = inputValue >> 0;
1101 | ```
1102 |
1103 | - **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:
1104 |
1105 | ```javascript
1106 | 2147483647 >> 0 //=> 2147483647
1107 | 2147483648 >> 0 //=> -2147483648
1108 | 2147483649 >> 0 //=> -2147483647
1109 | ```
1110 |
1111 | - Booleans:
1112 |
1113 | ```javascript
1114 | var age = 0;
1115 |
1116 | // bad
1117 | var hasAge = new Boolean(age);
1118 |
1119 | // good
1120 | var hasAge = Boolean(age);
1121 |
1122 | // good
1123 | var hasAge = !!age;
1124 | ```
1125 |
1126 | **[⬆ back to top](#table-of-contents)**
1127 |
1128 |
1129 | ## Naming Conventions
1130 |
1131 | - Avoid single letter names. Be descriptive with your naming.
1132 |
1133 | ```javascript
1134 | // bad
1135 | function q() {
1136 | // ...stuff...
1137 | }
1138 |
1139 | // good
1140 | function query() {
1141 | // ..stuff..
1142 | }
1143 | ```
1144 |
1145 | - Use camelCase when naming objects, functions, and instances.
1146 |
1147 | ```javascript
1148 | // bad
1149 | var OBJEcttsssss = {};
1150 | var this_is_my_object = {};
1151 | var o = {};
1152 | function c() {}
1153 |
1154 | // good
1155 | var thisIsMyObject = {};
1156 | function thisIsMyFunction() {}
1157 | ```
1158 |
1159 | - Use PascalCase when naming constructors or classes.
1160 |
1161 | ```javascript
1162 | // bad
1163 | function user(options) {
1164 | this.name = options.name;
1165 | }
1166 |
1167 | var bad = new user({
1168 | name: 'nope'
1169 | });
1170 |
1171 | // good
1172 | function User(options) {
1173 | this.name = options.name;
1174 | }
1175 |
1176 | var good = new User({
1177 | name: 'yup'
1178 | });
1179 | ```
1180 |
1181 | - Use a leading underscore `_` when naming private properties.
1182 |
1183 | ```javascript
1184 | // bad
1185 | this.__firstName__ = 'Panda';
1186 | this.firstName_ = 'Panda';
1187 |
1188 | // good
1189 | this._firstName = 'Panda';
1190 | ```
1191 |
1192 | - When saving a reference to `this` use `_this`.
1193 |
1194 | ```javascript
1195 | // bad
1196 | function() {
1197 | var self = this;
1198 | return function() {
1199 | console.log(self);
1200 | };
1201 | }
1202 |
1203 | // bad
1204 | function() {
1205 | var that = this;
1206 | return function() {
1207 | console.log(that);
1208 | };
1209 | }
1210 |
1211 | // good
1212 | function() {
1213 | var _this = this;
1214 | return function() {
1215 | console.log(_this);
1216 | };
1217 | }
1218 | ```
1219 |
1220 | - Name your functions. This is helpful for stack traces.
1221 |
1222 | ```javascript
1223 | // bad
1224 | var log = function(msg) {
1225 | console.log(msg);
1226 | };
1227 |
1228 | // good
1229 | var log = function log(msg) {
1230 | console.log(msg);
1231 | };
1232 | ```
1233 |
1234 | - **Note:** IE8 and below exhibit some quirks with named function expressions. See [http://kangax.github.io/nfe/](http://kangax.github.io/nfe/) for more info.
1235 |
1236 | - If your file exports a single class, your filename should be exactly the name of the class.
1237 | ```javascript
1238 | // file contents
1239 | class CheckBox {
1240 | // ...
1241 | }
1242 | module.exports = CheckBox;
1243 |
1244 | // in some other file
1245 | // bad
1246 | var CheckBox = require('./checkBox');
1247 |
1248 | // bad
1249 | var CheckBox = require('./check_box');
1250 |
1251 | // good
1252 | var CheckBox = require('./CheckBox');
1253 | ```
1254 |
1255 | **[⬆ back to top](#table-of-contents)**
1256 |
1257 |
1258 | ## Accessors
1259 |
1260 | - Accessor functions for properties are not required.
1261 | - If you do make accessor functions use getVal() and setVal('hello').
1262 |
1263 | ```javascript
1264 | // bad
1265 | dragon.age();
1266 |
1267 | // good
1268 | dragon.getAge();
1269 |
1270 | // bad
1271 | dragon.age(25);
1272 |
1273 | // good
1274 | dragon.setAge(25);
1275 | ```
1276 |
1277 | - If the property is a boolean, use isVal() or hasVal().
1278 |
1279 | ```javascript
1280 | // bad
1281 | if (!dragon.age()) {
1282 | return false;
1283 | }
1284 |
1285 | // good
1286 | if (!dragon.hasAge()) {
1287 | return false;
1288 | }
1289 | ```
1290 |
1291 | - It's okay to create get() and set() functions, but be consistent.
1292 |
1293 | ```javascript
1294 | function Jedi(options) {
1295 | options || (options = {});
1296 | var lightsaber = options.lightsaber || 'blue';
1297 | this.set('lightsaber', lightsaber);
1298 | }
1299 |
1300 | Jedi.prototype.set = function(key, val) {
1301 | this[key] = val;
1302 | };
1303 |
1304 | Jedi.prototype.get = function(key) {
1305 | return this[key];
1306 | };
1307 | ```
1308 |
1309 | **[⬆ back to top](#table-of-contents)**
1310 |
1311 |
1312 | ## Constructors
1313 |
1314 | - 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!
1315 |
1316 | ```javascript
1317 | function Jedi() {
1318 | console.log('new jedi');
1319 | }
1320 |
1321 | // bad
1322 | Jedi.prototype = {
1323 | fight: function fight() {
1324 | console.log('fighting');
1325 | },
1326 |
1327 | block: function block() {
1328 | console.log('blocking');
1329 | }
1330 | };
1331 |
1332 | // good
1333 | Jedi.prototype.fight = function fight() {
1334 | console.log('fighting');
1335 | };
1336 |
1337 | Jedi.prototype.block = function block() {
1338 | console.log('blocking');
1339 | };
1340 | ```
1341 |
1342 | - Methods can return `this` to help with method chaining.
1343 |
1344 | ```javascript
1345 | // bad
1346 | Jedi.prototype.jump = function() {
1347 | this.jumping = true;
1348 | return true;
1349 | };
1350 |
1351 | Jedi.prototype.setHeight = function(height) {
1352 | this.height = height;
1353 | };
1354 |
1355 | var luke = new Jedi();
1356 | luke.jump(); // => true
1357 | luke.setHeight(20); // => undefined
1358 |
1359 | // good
1360 | Jedi.prototype.jump = function() {
1361 | this.jumping = true;
1362 | return this;
1363 | };
1364 |
1365 | Jedi.prototype.setHeight = function(height) {
1366 | this.height = height;
1367 | return this;
1368 | };
1369 |
1370 | var luke = new Jedi();
1371 |
1372 | luke.jump()
1373 | .setHeight(20);
1374 | ```
1375 |
1376 |
1377 | - It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.
1378 |
1379 | ```javascript
1380 | function Jedi(options) {
1381 | options || (options = {});
1382 | this.name = options.name || 'no name';
1383 | }
1384 |
1385 | Jedi.prototype.getName = function getName() {
1386 | return this.name;
1387 | };
1388 |
1389 | Jedi.prototype.toString = function toString() {
1390 | return 'Jedi - ' + this.getName();
1391 | };
1392 | ```
1393 |
1394 | **[⬆ back to top](#table-of-contents)**
1395 |
1396 |
1397 | ## Events
1398 |
1399 | - 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:
1400 |
1401 | ```js
1402 | // bad
1403 | $(this).trigger('listingUpdated', listing.id);
1404 |
1405 | ...
1406 |
1407 | $(this).on('listingUpdated', function(e, listingId) {
1408 | // do something with listingId
1409 | });
1410 | ```
1411 |
1412 | prefer:
1413 |
1414 | ```js
1415 | // good
1416 | $(this).trigger('listingUpdated', { listingId : listing.id });
1417 |
1418 | ...
1419 |
1420 | $(this).on('listingUpdated', function(e, data) {
1421 | // do something with data.listingId
1422 | });
1423 | ```
1424 |
1425 | **[⬆ back to top](#table-of-contents)**
1426 |
1427 |
1428 | ## Modules
1429 |
1430 | - 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)
1431 | - The file should be named with camelCase, live in a folder with the same name, and match the name of the single export.
1432 | - Add a method called `noConflict()` that sets the exported module to the previous version and returns this one.
1433 | - Always declare `'use strict';` at the top of the module.
1434 |
1435 | ```javascript
1436 | // fancyInput/fancyInput.js
1437 |
1438 | !function(global) {
1439 | 'use strict';
1440 |
1441 | var previousFancyInput = global.FancyInput;
1442 |
1443 | function FancyInput(options) {
1444 | this.options = options || {};
1445 | }
1446 |
1447 | FancyInput.noConflict = function noConflict() {
1448 | global.FancyInput = previousFancyInput;
1449 | return FancyInput;
1450 | };
1451 |
1452 | global.FancyInput = FancyInput;
1453 | }(this);
1454 | ```
1455 |
1456 | **[⬆ back to top](#table-of-contents)**
1457 |
1458 |
1459 | ## jQuery
1460 |
1461 | - Prefix jQuery object variables with a `$`.
1462 |
1463 | ```javascript
1464 | // bad
1465 | var sidebar = $('.sidebar');
1466 |
1467 | // good
1468 | var $sidebar = $('.sidebar');
1469 | ```
1470 |
1471 | - Cache jQuery lookups.
1472 |
1473 | ```javascript
1474 | // bad
1475 | function setSidebar() {
1476 | $('.sidebar').hide();
1477 |
1478 | // ...stuff...
1479 |
1480 | $('.sidebar').css({
1481 | 'background-color': 'pink'
1482 | });
1483 | }
1484 |
1485 | // good
1486 | function setSidebar() {
1487 | var $sidebar = $('.sidebar');
1488 | $sidebar.hide();
1489 |
1490 | // ...stuff...
1491 |
1492 | $sidebar.css({
1493 | 'background-color': 'pink'
1494 | });
1495 | }
1496 | ```
1497 |
1498 | - For DOM queries use Cascading `$('.sidebar ul')` or parent > child `$('.sidebar > ul')`. [jsPerf](http://jsperf.com/jquery-find-vs-context-sel/16)
1499 | - Use `find` with scoped jQuery object queries.
1500 |
1501 | ```javascript
1502 | // bad
1503 | $('ul', '.sidebar').hide();
1504 |
1505 | // bad
1506 | $('.sidebar').find('ul').hide();
1507 |
1508 | // good
1509 | $('.sidebar ul').hide();
1510 |
1511 | // good
1512 | $('.sidebar > ul').hide();
1513 |
1514 | // good
1515 | $sidebar.find('ul').hide();
1516 | ```
1517 |
1518 | **[⬆ back to top](#table-of-contents)**
1519 |
1520 |
1521 | ## ECMAScript 5 Compatibility
1522 |
1523 | - Refer to [Kangax](https://twitter.com/kangax/)'s ES5 [compatibility table](http://kangax.github.com/es5-compat-table/).
1524 |
1525 | **[⬆ back to top](#table-of-contents)**
1526 |
1527 |
1528 | ## Testing
1529 |
1530 | - **Yup.**
1531 |
1532 | ```javascript
1533 | function() {
1534 | return true;
1535 | }
1536 | ```
1537 |
1538 | **[⬆ back to top](#table-of-contents)**
1539 |
1540 |
1541 | ## Performance
1542 |
1543 | - [On Layout & Web Performance](http://kellegous.com/j/2013/01/26/layout-performance/)
1544 | - [String vs Array Concat](http://jsperf.com/string-vs-array-concat/2)
1545 | - [Try/Catch Cost In a Loop](http://jsperf.com/try-catch-in-loop-cost)
1546 | - [Bang Function](http://jsperf.com/bang-function)
1547 | - [jQuery Find vs Context, Selector](http://jsperf.com/jquery-find-vs-context-sel/13)
1548 | - [innerHTML vs textContent for script text](http://jsperf.com/innerhtml-vs-textcontent-for-script-text)
1549 | - [Long String Concatenation](http://jsperf.com/ya-string-concat)
1550 | - Loading...
1551 |
1552 | **[⬆ back to top](#table-of-contents)**
1553 |
1554 |
1555 | ## Resources
1556 |
1557 |
1558 | **Read This**
1559 |
1560 | - [Annotated ECMAScript 5.1](http://es5.github.com/)
1561 |
1562 | **Tools**
1563 |
1564 | - Code Style Linters
1565 | + [JSHint](http://www.jshint.com/) - [Airbnb Style .jshintrc](https://github.com/airbnb/javascript/blob/master/linters/jshintrc)
1566 | + [JSCS](https://github.com/jscs-dev/node-jscs) - [Airbnb Style Preset](https://github.com/jscs-dev/node-jscs/blob/master/presets/airbnb.json)
1567 |
1568 | **Other Style Guides**
1569 |
1570 | - [Google JavaScript Style Guide](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml)
1571 | - [jQuery Core Style Guidelines](http://docs.jquery.com/JQuery_Core_Style_Guidelines)
1572 | - [Principles of Writing Consistent, Idiomatic JavaScript](https://github.com/rwldrn/idiomatic.js/)
1573 | - [JavaScript Standard Style](https://github.com/feross/standard)
1574 |
1575 | **Other Styles**
1576 |
1577 | - [Naming this in nested functions](https://gist.github.com/4135065) - Christian Johansen
1578 | - [Conditional Callbacks](https://github.com/airbnb/javascript/issues/52) - Ross Allen
1579 | - [Popular JavaScript Coding Conventions on Github](http://sideeffect.kr/popularconvention/#javascript) - JeongHoon Byun
1580 | - [Multiple var statements in JavaScript, not superfluous](http://benalman.com/news/2012/05/multiple-var-statements-javascript/) - Ben Alman
1581 |
1582 | **Further Reading**
1583 |
1584 | - [Understanding JavaScript Closures](http://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/) - Angus Croll
1585 | - [Basic JavaScript for the impatient programmer](http://www.2ality.com/2013/06/basic-javascript.html) - Dr. Axel Rauschmayer
1586 | - [You Might Not Need jQuery](http://youmightnotneedjquery.com/) - Zack Bloom & Adam Schwartz
1587 | - [ES6 Features](https://github.com/lukehoban/es6features) - Luke Hoban
1588 | - [Frontend Guidelines](https://github.com/bendc/frontend-guidelines) - Benjamin De Cock
1589 |
1590 | **Books**
1591 |
1592 | - [JavaScript: The Good Parts](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) - Douglas Crockford
1593 | - [JavaScript Patterns](http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752) - Stoyan Stefanov
1594 | - [Pro JavaScript Design Patterns](http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X) - Ross Harmes and Dustin Diaz
1595 | - [High Performance Web Sites: Essential Knowledge for Front-End Engineers](http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309) - Steve Souders
1596 | - [Maintainable JavaScript](http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680) - Nicholas C. Zakas
1597 | - [JavaScript Web Applications](http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X) - Alex MacCaw
1598 | - [Pro JavaScript Techniques](http://www.amazon.com/Pro-JavaScript-Techniques-John-Resig/dp/1590597273) - John Resig
1599 | - [Smashing Node.js: JavaScript Everywhere](http://www.amazon.com/Smashing-Node-js-JavaScript-Everywhere-Magazine/dp/1119962595) - Guillermo Rauch
1600 | - [Secrets of the JavaScript Ninja](http://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/193398869X) - John Resig and Bear Bibeault
1601 | - [Human JavaScript](http://humanjavascript.com/) - Henrik Joreteg
1602 | - [Superhero.js](http://superherojs.com/) - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy
1603 | - [JSBooks](http://jsbooks.revolunet.com/) - Julien Bouquillon
1604 | - [Third Party JavaScript](http://manning.com/vinegar/) - Ben Vinegar and Anton Kovalyov
1605 | - [Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript](http://amzn.com/0321812182) - David Herman
1606 | - [Eloquent JavaScript](http://eloquentjavascript.net) - Marijn Haverbeke
1607 | - [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS) - Kyle Simpson
1608 |
1609 | **Blogs**
1610 |
1611 | - [DailyJS](http://dailyjs.com/)
1612 | - [JavaScript Weekly](http://javascriptweekly.com/)
1613 | - [JavaScript, JavaScript...](http://javascriptweblog.wordpress.com/)
1614 | - [Bocoup Weblog](http://weblog.bocoup.com/)
1615 | - [Adequately Good](http://www.adequatelygood.com/)
1616 | - [NCZOnline](http://www.nczonline.net/)
1617 | - [Perfection Kills](http://perfectionkills.com/)
1618 | - [Ben Alman](http://benalman.com/)
1619 | - [Dmitry Baranovskiy](http://dmitry.baranovskiy.com/)
1620 | - [Dustin Diaz](http://dustindiaz.com/)
1621 | - [nettuts](http://net.tutsplus.com/?s=javascript)
1622 |
1623 | **Podcasts**
1624 |
1625 | - [JavaScript Jabber](http://devchat.tv/js-jabber/)
1626 |
1627 |
1628 | **[⬆ back to top](#table-of-contents)**
1629 |
1630 | ## In the Wild
1631 |
1632 | 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.
1633 |
1634 | - **Aan Zee**: [AanZee/javascript](https://github.com/AanZee/javascript)
1635 | - **Adult Swim**: [adult-swim/javascript](https://github.com/adult-swim/javascript)
1636 | - **Airbnb**: [airbnb/javascript](https://github.com/airbnb/javascript)
1637 | - **Apartmint**: [apartmint/javascript](https://github.com/apartmint/javascript)
1638 | - **Avalara**: [avalara/javascript](https://github.com/avalara/javascript)
1639 | - **Billabong**: [billabong/javascript](https://github.com/billabong/javascript)
1640 | - **Compass Learning**: [compasslearning/javascript-style-guide](https://github.com/compasslearning/javascript-style-guide)
1641 | - **DailyMotion**: [dailymotion/javascript](https://github.com/dailymotion/javascript)
1642 | - **Digitpaint** [digitpaint/javascript](https://github.com/digitpaint/javascript)
1643 | - **Evernote**: [evernote/javascript-style-guide](https://github.com/evernote/javascript-style-guide)
1644 | - **ExactTarget**: [ExactTarget/javascript](https://github.com/ExactTarget/javascript)
1645 | - **Flexberry**: [Flexberry/javascript-style-guide](https://github.com/Flexberry/javascript-style-guide)
1646 | - **Gawker Media**: [gawkermedia/javascript](https://github.com/gawkermedia/javascript)
1647 | - **General Electric**: [GeneralElectric/javascript](https://github.com/GeneralElectric/javascript)
1648 | - **GoodData**: [gooddata/gdc-js-style](https://github.com/gooddata/gdc-js-style)
1649 | - **Grooveshark**: [grooveshark/javascript](https://github.com/grooveshark/javascript)
1650 | - **How About We**: [howaboutwe/javascript](https://github.com/howaboutwe/javascript)
1651 | - **InfoJobs**: [InfoJobs/JavaScript-Style-Guide](https://github.com/InfoJobs/JavaScript-Style-Guide)
1652 | - **Intent Media**: [intentmedia/javascript](https://github.com/intentmedia/javascript)
1653 | - **Jam3**: [Jam3/Javascript-Code-Conventions](https://github.com/Jam3/Javascript-Code-Conventions)
1654 | - **JSSolutions**: [JSSolutions/javascript](https://github.com/JSSolutions/javascript)
1655 | - **Kinetica Solutions**: [kinetica/javascript](https://github.com/kinetica/javascript)
1656 | - **Mighty Spring**: [mightyspring/javascript](https://github.com/mightyspring/javascript)
1657 | - **MinnPost**: [MinnPost/javascript](https://github.com/MinnPost/javascript)
1658 | - **ModCloth**: [modcloth/javascript](https://github.com/modcloth/javascript)
1659 | - **Money Advice Service**: [moneyadviceservice/javascript](https://github.com/moneyadviceservice/javascript)
1660 | - **Muber**: [muber/javascript](https://github.com/muber/javascript)
1661 | - **National Geographic**: [natgeo/javascript](https://github.com/natgeo/javascript)
1662 | - **National Park Service**: [nationalparkservice/javascript](https://github.com/nationalparkservice/javascript)
1663 | - **Nimbl3**: [nimbl3/javascript](https://github.com/nimbl3/javascript)
1664 | - **Nordic Venture Family**: [CodeDistillery/javascript](https://github.com/CodeDistillery/javascript)
1665 | - **Orion Health**: [orionhealth/javascript](https://github.com/orionhealth/javascript)
1666 | - **Peerby**: [Peerby/javascript](https://github.com/Peerby/javascript)
1667 | - **Razorfish**: [razorfish/javascript-style-guide](https://github.com/razorfish/javascript-style-guide)
1668 | - **reddit**: [reddit/styleguide/javascript](https://github.com/reddit/styleguide/tree/master/javascript)
1669 | - **REI**: [reidev/js-style-guide](https://github.com/reidev/js-style-guide)
1670 | - **Ripple**: [ripple/javascript-style-guide](https://github.com/ripple/javascript-style-guide)
1671 | - **SeekingAlpha**: [seekingalpha/javascript-style-guide](https://github.com/seekingalpha/javascript-style-guide)
1672 | - **Shutterfly**: [shutterfly/javascript](https://github.com/shutterfly/javascript)
1673 | - **StudentSphere**: [studentsphere/javascript](https://github.com/studentsphere/javascript)
1674 | - **Target**: [target/javascript](https://github.com/target/javascript)
1675 | - **TheLadders**: [TheLadders/javascript](https://github.com/TheLadders/javascript)
1676 | - **T4R Technology**: [T4R-Technology/javascript](https://github.com/T4R-Technology/javascript)
1677 | - **VoxFeed**: [VoxFeed/javascript-style-guide](https://github.com/VoxFeed/javascript-style-guide)
1678 | - **Weggo**: [Weggo/javascript](https://github.com/Weggo/javascript)
1679 | - **Zillow**: [zillow/javascript](https://github.com/zillow/javascript)
1680 | - **ZocDoc**: [ZocDoc/javascript](https://github.com/ZocDoc/javascript)
1681 |
1682 | ## Translation
1683 |
1684 | This style guide is also available in other languages:
1685 |
1686 | -  **Brazilian Portuguese**: [armoucar/javascript-style-guide](https://github.com/armoucar/javascript-style-guide)
1687 | -  **Bulgarian**: [borislavvv/javascript](https://github.com/borislavvv/javascript)
1688 | -  **Catalan**: [fpmweb/javascript-style-guide](https://github.com/fpmweb/javascript-style-guide)
1689 | -  **Chinese(Traditional)**: [jigsawye/javascript](https://github.com/jigsawye/javascript)
1690 | -  **Chinese(Simplified)**: [sivan/javascript-style-guide](https://github.com/sivan/javascript-style-guide)
1691 | -  **French**: [nmussy/javascript-style-guide](https://github.com/nmussy/javascript-style-guide)
1692 | -  **German**: [timofurrer/javascript-style-guide](https://github.com/timofurrer/javascript-style-guide)
1693 | -  **Italian**: [sinkswim/javascript-style-guide](https://github.com/sinkswim/javascript-style-guide)
1694 | -  **Japanese**: [mitsuruog/javacript-style-guide](https://github.com/mitsuruog/javacript-style-guide)
1695 | -  **Korean**: [tipjs/javascript-style-guide](https://github.com/tipjs/javascript-style-guide)
1696 | -  **Polish**: [mjurczyk/javascript](https://github.com/mjurczyk/javascript)
1697 | -  **Russian**: [uprock/javascript](https://github.com/uprock/javascript)
1698 | -  **Spanish**: [paolocarrasco/javascript-style-guide](https://github.com/paolocarrasco/javascript-style-guide)
1699 | -  **Thai**: [lvarayut/javascript-style-guide](https://github.com/lvarayut/javascript-style-guide)
1700 |
1701 | ## The JavaScript Style Guide Guide
1702 |
1703 | - [Reference](https://github.com/airbnb/javascript/wiki/The-JavaScript-Style-Guide-Guide)
1704 |
1705 | ## Chat With Us About JavaScript
1706 |
1707 | - Find us on [gitter](https://gitter.im/airbnb/javascript).
1708 |
1709 | ## Contributors
1710 |
1711 | - [View Contributors](https://github.com/airbnb/javascript/graphs/contributors)
1712 |
1713 |
1714 | ## License
1715 |
1716 | (The MIT License)
1717 |
1718 | Copyright (c) 2014 Airbnb
1719 |
1720 | Permission is hereby granted, free of charge, to any person obtaining
1721 | a copy of this software and associated documentation files (the
1722 | 'Software'), to deal in the Software without restriction, including
1723 | without limitation the rights to use, copy, modify, merge, publish,
1724 | distribute, sublicense, and/or sell copies of the Software, and to
1725 | permit persons to whom the Software is furnished to do so, subject to
1726 | the following conditions:
1727 |
1728 | The above copyright notice and this permission notice shall be
1729 | included in all copies or substantial portions of the Software.
1730 |
1731 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
1732 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1733 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
1734 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
1735 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
1736 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
1737 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1738 |
1739 | **[⬆ back to top](#table-of-contents)**
1740 |
1741 | # };
1742 |
--------------------------------------------------------------------------------
/linters/.eslintrc:
--------------------------------------------------------------------------------
1 | // Use this file as a starting point for your project's .eslintrc.
2 | // Copy this file, and add rule overrides as needed.
3 | {
4 | "extends": "airbnb"
5 | }
6 |
--------------------------------------------------------------------------------
/linters/README.md:
--------------------------------------------------------------------------------
1 | ## `.eslintrc`
2 |
3 | Our `.eslintrc` requires the following NPM packages:
4 |
5 | - `eslint-config-airbnb`
6 | - `eslint`
7 | - `babel-eslint`
8 | - `eslint-plugin-react`
9 |
--------------------------------------------------------------------------------
/linters/SublimeLinter/SublimeLinter.sublime-settings:
--------------------------------------------------------------------------------
1 | /**
2 | * Airbnb JSHint settings for use with SublimeLinter and Sublime Text 2.
3 | *
4 | * 1. Install SublimeLinter at https://github.com/SublimeLinter/SublimeLinter
5 | * 2. Open user preferences for the SublimeLinter package in Sublime Text 2
6 | * * For Mac OS X go to _Sublime Text 2_ > _Preferences_ > _Package Settings_ > _SublimeLinter_ > _Settings - User_
7 | * 3. Paste the contents of this file into your settings file
8 | * 4. Save the settings file
9 | *
10 | * @version 0.3.0
11 | * @see https://github.com/SublimeLinter/SublimeLinter
12 | * @see http://www.jshint.com/docs/
13 | */
14 | {
15 | "jshint_options":
16 | {
17 | /*
18 | * ENVIRONMENTS
19 | * =================
20 | */
21 |
22 | // Define globals exposed by modern browsers.
23 | "browser": true,
24 |
25 | // Define globals exposed by jQuery.
26 | "jquery": true,
27 |
28 | // Define globals exposed by Node.js.
29 | "node": true,
30 |
31 | /*
32 | * ENFORCING OPTIONS
33 | * =================
34 | */
35 |
36 | // Force all variable names to use either camelCase style or UPPER_CASE
37 | // with underscores.
38 | "camelcase": true,
39 |
40 | // Prohibit use of == and != in favor of === and !==.
41 | "eqeqeq": true,
42 |
43 | // Suppress warnings about == null comparisons.
44 | "eqnull": true,
45 |
46 | // Enforce tab width of 2 spaces.
47 | "indent": 2,
48 |
49 | // Prohibit use of a variable before it is defined.
50 | "latedef": true,
51 |
52 | // Require capitalized names for constructor functions.
53 | "newcap": true,
54 |
55 | // Enforce use of single quotation marks for strings.
56 | "quotmark": "single",
57 |
58 | // Prohibit trailing whitespace.
59 | "trailing": true,
60 |
61 | // Prohibit use of explicitly undeclared variables.
62 | "undef": true,
63 |
64 | // Warn when variables are defined but never used.
65 | "unused": true,
66 |
67 | // Enforce line length to 80 characters
68 | "maxlen": 80,
69 |
70 | // Enforce placing 'use strict' at the top function scope
71 | "strict": true
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/linters/jshintrc:
--------------------------------------------------------------------------------
1 | {
2 | /*
3 | * ENVIRONMENTS
4 | * =================
5 | */
6 |
7 | // Define globals exposed by modern browsers.
8 | "browser": true,
9 |
10 | // Define globals exposed by jQuery.
11 | "jquery": true,
12 |
13 | // Define globals exposed by Node.js.
14 | "node": true,
15 |
16 | // Allow ES6.
17 | "esnext": true,
18 |
19 | /*
20 | * ENFORCING OPTIONS
21 | * =================
22 | */
23 |
24 | // Force all variable names to use either camelCase style or UPPER_CASE
25 | // with underscores.
26 | "camelcase": true,
27 |
28 | // Prohibit use of == and != in favor of === and !==.
29 | "eqeqeq": true,
30 |
31 | // Enforce tab width of 2 spaces.
32 | "indent": 2,
33 |
34 | // Prohibit use of a variable before it is defined.
35 | "latedef": true,
36 |
37 | // Enforce line length to 80 characters
38 | "maxlen": 80,
39 |
40 | // Require capitalized names for constructor functions.
41 | "newcap": true,
42 |
43 | // Enforce use of single quotation marks for strings.
44 | "quotmark": "single",
45 |
46 | // Enforce placing 'use strict' at the top function scope
47 | "strict": true,
48 |
49 | // Prohibit use of explicitly undeclared variables.
50 | "undef": true,
51 |
52 | // Warn when variables are defined but never used.
53 | "unused": true,
54 |
55 | /*
56 | * RELAXING OPTIONS
57 | * =================
58 | */
59 |
60 | // Suppress warnings about == null comparisons.
61 | "eqnull": true
62 | }
63 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "airbnb-style",
3 | "version": "2.0.0",
4 | "description": "A mostly reasonable approach to JavaScript.",
5 | "scripts": {
6 | "test": "echo \"Error: no test specified\" && exit 1",
7 | "publish-all": "npm publish && cd ./packages/eslint-config-airbnb && npm publish"
8 | },
9 | "repository": {
10 | "type": "git",
11 | "url": "https://github.com/airbnb/javascript.git"
12 | },
13 | "keywords": [
14 | "style guide",
15 | "lint",
16 | "airbnb",
17 | "es6",
18 | "es2015",
19 | "react",
20 | "jsx"
21 | ],
22 | "author": "Harrison Shoff (https://twitter.com/hshoff)",
23 | "license": "MIT",
24 | "bugs": {
25 | "url": "https://github.com/airbnb/javascript/issues"
26 | },
27 | "homepage": "https://github.com/airbnb/javascript"
28 | }
29 |
--------------------------------------------------------------------------------
/packages/eslint-config-airbnb/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "airbnb",
3 | "rules": {
4 | // disable requiring trailing commas because it might be nice to revert to
5 | // being JSON at some point, and I don't want to make big changes now.
6 | "comma-dangle": 0,
7 | // disabled because I find it tedious to write tests while following this
8 | // rule
9 | "no-shadow": 0
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/packages/eslint-config-airbnb/README.md:
--------------------------------------------------------------------------------
1 | # eslint-config-airbnb
2 |
3 | This package provides Airbnb's .eslintrc as an extensible shared config.
4 |
5 | ## Usage
6 |
7 | ### With React Style
8 |
9 | 1. `npm install --save-dev eslint-config-airbnb babel-eslint eslint-plugin-react`
10 | 2. add `"extends": "airbnb"` to your .eslintrc
11 |
12 | ### Without React Style
13 |
14 | 1. `npm install --save-dev eslint-config-airbnb babel-eslint `
15 | 2. add `"extends": "airbnb/base"` to your .eslintrc
16 |
17 | See [Airbnb's Javascript styleguide](https://github.com/airbnb/javascript) and
18 | the [ESlint config docs](http://eslint.org/docs/user-guide/configuring#extending-configuration-files)
19 | for more information.
20 |
21 | ## Improving this config
22 |
23 | Consider adding test cases if you're making complicated rules changes, like
24 | anything involving regexes. Perhaps in a distant future, we could use literate
25 | programming to structure our README as test cases for our .eslintrc?
26 |
27 | You can run tests with `npm test`.
28 |
29 | You can make sure this module lints with itself using `npm run lint`.
30 |
--------------------------------------------------------------------------------
/packages/eslint-config-airbnb/base/index.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | 'parser': 'babel-eslint', // https://github.com/babel/babel-eslint
3 | 'env': { // http://eslint.org/docs/user-guide/configuring.html#specifying-environments
4 | 'browser': true, // browser global variables
5 | 'node': true // Node.js global variables and Node.js-specific rules
6 | },
7 | 'ecmaFeatures': {
8 | 'arrowFunctions': true,
9 | 'blockBindings': true,
10 | 'classes': true,
11 | 'defaultParams': true,
12 | 'destructuring': true,
13 | 'forOf': true,
14 | 'generators': false,
15 | 'modules': true,
16 | 'objectLiteralComputedProperties': true,
17 | 'objectLiteralDuplicateProperties': false,
18 | 'objectLiteralShorthandMethods': true,
19 | 'objectLiteralShorthandProperties': true,
20 | 'spread': true,
21 | 'superInFunctions': true,
22 | 'templateStrings': true,
23 | 'jsx': true
24 | },
25 | 'rules': {
26 | /**
27 | * Strict mode
28 | */
29 | // babel inserts 'use strict'; for us
30 | 'strict': [2, 'never'], // http://eslint.org/docs/rules/strict
31 |
32 | /**
33 | * ES6
34 | */
35 | 'no-var': 2, // http://eslint.org/docs/rules/no-var
36 | 'prefer-const': 2, // http://eslint.org/docs/rules/prefer-const
37 |
38 | /**
39 | * Variables
40 | */
41 | 'no-shadow': 2, // http://eslint.org/docs/rules/no-shadow
42 | 'no-shadow-restricted-names': 2, // http://eslint.org/docs/rules/no-shadow-restricted-names
43 | 'no-unused-vars': [2, { // http://eslint.org/docs/rules/no-unused-vars
44 | 'vars': 'local',
45 | 'args': 'after-used'
46 | }],
47 | 'no-use-before-define': 2, // http://eslint.org/docs/rules/no-use-before-define
48 |
49 | /**
50 | * Possible errors
51 | */
52 | 'comma-dangle': [2, 'always-multiline'], // http://eslint.org/docs/rules/comma-dangle
53 | 'no-cond-assign': [2, 'always'], // http://eslint.org/docs/rules/no-cond-assign
54 | 'no-console': 1, // http://eslint.org/docs/rules/no-console
55 | 'no-debugger': 1, // http://eslint.org/docs/rules/no-debugger
56 | 'no-alert': 1, // http://eslint.org/docs/rules/no-alert
57 | 'no-constant-condition': 1, // http://eslint.org/docs/rules/no-constant-condition
58 | 'no-dupe-keys': 2, // http://eslint.org/docs/rules/no-dupe-keys
59 | 'no-duplicate-case': 2, // http://eslint.org/docs/rules/no-duplicate-case
60 | 'no-empty': 2, // http://eslint.org/docs/rules/no-empty
61 | 'no-ex-assign': 2, // http://eslint.org/docs/rules/no-ex-assign
62 | 'no-extra-boolean-cast': 0, // http://eslint.org/docs/rules/no-extra-boolean-cast
63 | 'no-extra-semi': 2, // http://eslint.org/docs/rules/no-extra-semi
64 | 'no-func-assign': 2, // http://eslint.org/docs/rules/no-func-assign
65 | 'no-inner-declarations': 2, // http://eslint.org/docs/rules/no-inner-declarations
66 | 'no-invalid-regexp': 2, // http://eslint.org/docs/rules/no-invalid-regexp
67 | 'no-irregular-whitespace': 2, // http://eslint.org/docs/rules/no-irregular-whitespace
68 | 'no-obj-calls': 2, // http://eslint.org/docs/rules/no-obj-calls
69 | 'no-sparse-arrays': 2, // http://eslint.org/docs/rules/no-sparse-arrays
70 | 'no-unreachable': 2, // http://eslint.org/docs/rules/no-unreachable
71 | 'use-isnan': 2, // http://eslint.org/docs/rules/use-isnan
72 | 'block-scoped-var': 2, // http://eslint.org/docs/rules/block-scoped-var
73 |
74 | /**
75 | * Best practices
76 | */
77 | 'consistent-return': 2, // http://eslint.org/docs/rules/consistent-return
78 | 'curly': [2, 'multi-line'], // http://eslint.org/docs/rules/curly
79 | 'default-case': 2, // http://eslint.org/docs/rules/default-case
80 | 'dot-notation': [2, { // http://eslint.org/docs/rules/dot-notation
81 | 'allowKeywords': true
82 | }],
83 | 'eqeqeq': 2, // http://eslint.org/docs/rules/eqeqeq
84 | 'guard-for-in': 2, // http://eslint.org/docs/rules/guard-for-in
85 | 'no-caller': 2, // http://eslint.org/docs/rules/no-caller
86 | 'no-else-return': 2, // http://eslint.org/docs/rules/no-else-return
87 | 'no-eq-null': 2, // http://eslint.org/docs/rules/no-eq-null
88 | 'no-eval': 2, // http://eslint.org/docs/rules/no-eval
89 | 'no-extend-native': 2, // http://eslint.org/docs/rules/no-extend-native
90 | 'no-extra-bind': 2, // http://eslint.org/docs/rules/no-extra-bind
91 | 'no-fallthrough': 2, // http://eslint.org/docs/rules/no-fallthrough
92 | 'no-floating-decimal': 2, // http://eslint.org/docs/rules/no-floating-decimal
93 | 'no-implied-eval': 2, // http://eslint.org/docs/rules/no-implied-eval
94 | 'no-lone-blocks': 2, // http://eslint.org/docs/rules/no-lone-blocks
95 | 'no-loop-func': 2, // http://eslint.org/docs/rules/no-loop-func
96 | 'no-multi-str': 2, // http://eslint.org/docs/rules/no-multi-str
97 | 'no-native-reassign': 2, // http://eslint.org/docs/rules/no-native-reassign
98 | 'no-new': 2, // http://eslint.org/docs/rules/no-new
99 | 'no-new-func': 2, // http://eslint.org/docs/rules/no-new-func
100 | 'no-new-wrappers': 2, // http://eslint.org/docs/rules/no-new-wrappers
101 | 'no-octal': 2, // http://eslint.org/docs/rules/no-octal
102 | 'no-octal-escape': 2, // http://eslint.org/docs/rules/no-octal-escape
103 | 'no-param-reassign': 2, // http://eslint.org/docs/rules/no-param-reassign
104 | 'no-proto': 2, // http://eslint.org/docs/rules/no-proto
105 | 'no-redeclare': 2, // http://eslint.org/docs/rules/no-redeclare
106 | 'no-return-assign': 2, // http://eslint.org/docs/rules/no-return-assign
107 | 'no-script-url': 2, // http://eslint.org/docs/rules/no-script-url
108 | 'no-self-compare': 2, // http://eslint.org/docs/rules/no-self-compare
109 | 'no-sequences': 2, // http://eslint.org/docs/rules/no-sequences
110 | 'no-throw-literal': 2, // http://eslint.org/docs/rules/no-throw-literal
111 | 'no-with': 2, // http://eslint.org/docs/rules/no-with
112 | 'radix': 2, // http://eslint.org/docs/rules/radix
113 | 'vars-on-top': 2, // http://eslint.org/docs/rules/vars-on-top
114 | 'wrap-iife': [2, 'any'], // http://eslint.org/docs/rules/wrap-iife
115 | 'yoda': 2, // http://eslint.org/docs/rules/yoda
116 |
117 | /**
118 | * Style
119 | */
120 | 'indent': [2, 2], // http://eslint.org/docs/rules/indent
121 | 'brace-style': [
122 | 2, // http://eslint.org/docs/rules/brace-style
123 | '1tbs', {
124 | 'allowSingleLine': true
125 | }
126 | ],
127 | 'quotes': [
128 | 2, 'single', 'avoid-escape' // http://eslint.org/docs/rules/quotes
129 | ],
130 | 'camelcase': [2, { // http://eslint.org/docs/rules/camelcase
131 | 'properties': 'never'
132 | }],
133 | 'comma-spacing': [2, { // http://eslint.org/docs/rules/comma-spacing
134 | 'before': false,
135 | 'after': true
136 | }],
137 | 'comma-style': [2, 'last'], // http://eslint.org/docs/rules/comma-style
138 | 'eol-last': 2, // http://eslint.org/docs/rules/eol-last
139 | 'func-names': 1, // http://eslint.org/docs/rules/func-names
140 | 'key-spacing': [2, { // http://eslint.org/docs/rules/key-spacing
141 | 'beforeColon': false,
142 | 'afterColon': true
143 | }],
144 | 'new-cap': [2, { // http://eslint.org/docs/rules/new-cap
145 | 'newIsCap': true
146 | }],
147 | 'no-multiple-empty-lines': [2, { // http://eslint.org/docs/rules/no-multiple-empty-lines
148 | 'max': 2
149 | }],
150 | 'no-nested-ternary': 2, // http://eslint.org/docs/rules/no-nested-ternary
151 | 'no-new-object': 2, // http://eslint.org/docs/rules/no-new-object
152 | 'no-spaced-func': 2, // http://eslint.org/docs/rules/no-spaced-func
153 | 'no-trailing-spaces': 2, // http://eslint.org/docs/rules/no-trailing-spaces
154 | 'no-extra-parens': [2, 'functions'], // http://eslint.org/docs/rules/no-extra-parens
155 | 'no-underscore-dangle': 0, // http://eslint.org/docs/rules/no-underscore-dangle
156 | 'one-var': [2, 'never'], // http://eslint.org/docs/rules/one-var
157 | 'padded-blocks': [2, 'never'], // http://eslint.org/docs/rules/padded-blocks
158 | 'semi': [2, 'always'], // http://eslint.org/docs/rules/semi
159 | 'semi-spacing': [2, { // http://eslint.org/docs/rules/semi-spacing
160 | 'before': false,
161 | 'after': true
162 | }],
163 | 'space-after-keywords': 2, // http://eslint.org/docs/rules/space-after-keywords
164 | 'space-before-blocks': 2, // http://eslint.org/docs/rules/space-before-blocks
165 | 'space-before-function-paren': [2, 'never'], // http://eslint.org/docs/rules/space-before-function-paren
166 | 'space-infix-ops': 2, // http://eslint.org/docs/rules/space-infix-ops
167 | 'space-return-throw-case': 2, // http://eslint.org/docs/rules/space-return-throw-case
168 | 'spaced-comment': [2, 'always', {// http://eslint.org/docs/rules/spaced-comment
169 | 'exceptions': ['-', '+'],
170 | 'markers': ['=', '!'] // space here to support sprockets directives
171 | }],
172 | }
173 | };
174 |
--------------------------------------------------------------------------------
/packages/eslint-config-airbnb/index.js:
--------------------------------------------------------------------------------
1 | const reactRules = require('./react');
2 | const base = require('./base');
3 |
4 | // clone this so we aren't mutating a module
5 | const eslintrc = JSON.parse(JSON.stringify(base));
6 |
7 | // manually merge in React rules
8 | eslintrc.plugins = reactRules.plugins;
9 | Object.keys(reactRules.rules).forEach(function assignRule(ruleId) {
10 | eslintrc.rules[ruleId] = reactRules.rules[ruleId];
11 | });
12 |
13 | module.exports = eslintrc;
14 |
--------------------------------------------------------------------------------
/packages/eslint-config-airbnb/node_modules/eslint-config-airbnb:
--------------------------------------------------------------------------------
1 | ..
--------------------------------------------------------------------------------
/packages/eslint-config-airbnb/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "eslint-config-airbnb",
3 | "version": "0.0.7",
4 | "description": "Airbnb's ESLint config, following our styleguide",
5 | "main": "index.js",
6 | "scripts": {
7 | "lint": "./node_modules/.bin/eslint .",
8 | "test": "./node_modules/.bin/babel-tape-runner ./test/test-*.js"
9 | },
10 | "repository": {
11 | "type": "git",
12 | "url": "https://github.com/airbnb/javascript"
13 | },
14 | "keywords": [
15 | "eslint",
16 | "eslintconfig",
17 | "config",
18 | "airbnb",
19 | "javascript",
20 | "styleguide"
21 | ],
22 | "author": "Jake Teton-Landis (https://twitter.com/@jitl)",
23 | "license": "MIT",
24 | "bugs": {
25 | "url": "https://github.com/airbnb/javascript/issues"
26 | },
27 | "homepage": "https://github.com/airbnb/javascript",
28 | "devDependencies": {
29 | "babel-eslint": "4.0.10",
30 | "babel-tape-runner": "1.2.0",
31 | "eslint": "1.1.0",
32 | "eslint-plugin-react": "3.2.3",
33 | "react": "0.13.3",
34 | "tape": "4.2.0"
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/packages/eslint-config-airbnb/react.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | 'plugins': [
3 | 'react' // https://github.com/yannickcr/eslint-plugin-react
4 | ],
5 | rules: {
6 | /**
7 | * JSX style
8 | */
9 | 'react/display-name': 0, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md
10 | 'react/jsx-boolean-value': 2, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md
11 | 'react/jsx-quotes': [2, 'double'], // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-quotes.md
12 | 'react/jsx-no-undef': 2, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-undef.md
13 | 'react/jsx-sort-props': 0, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md
14 | 'react/jsx-sort-prop-types': 0, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-prop-types.md
15 | 'react/jsx-uses-react': 2, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-react.md
16 | 'react/jsx-uses-vars': 2, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-vars.md
17 | 'react/no-did-mount-set-state': [2, 'allow-in-func'], // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md
18 | 'react/no-did-update-set-state': 2, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md
19 | 'react/no-multi-comp': 2, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-multi-comp.md
20 | 'react/no-unknown-property': 2, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unknown-property.md
21 | 'react/prop-types': 2, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md
22 | 'react/react-in-jsx-scope': 2, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md
23 | 'react/self-closing-comp': 2, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/self-closing-comp.md
24 | 'react/wrap-multilines': 2, // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/wrap-multilines.md
25 | 'react/sort-comp': [2, { // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-comp.md
26 | 'order': [
27 | 'lifecycle',
28 | '/^on.+$/',
29 | '/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/',
30 | 'everything-else',
31 | '/^render.+$/',
32 | 'render'
33 | ]
34 | }]
35 | }
36 | };
37 |
--------------------------------------------------------------------------------
/packages/eslint-config-airbnb/test/test-base.js:
--------------------------------------------------------------------------------
1 | import test from 'tape';
2 | import base from '../base';
3 |
4 | test('base: does not reference react', t => {
5 | t.plan(2);
6 |
7 | t.notOk(base.plugins, 'plugins is unspecified');
8 |
9 | // scan rules for react/ and fail if any exist
10 | const reactRuleIds = Object.keys(base.rules)
11 | .filter(ruleId => ruleId.indexOf('react/') === 0);
12 | t.deepEquals(reactRuleIds, [], 'there are no react/ rules');
13 | });
14 |
--------------------------------------------------------------------------------
/packages/eslint-config-airbnb/test/test-react-order.js:
--------------------------------------------------------------------------------
1 | import test from 'tape';
2 | import { CLIEngine } from 'eslint';
3 | import eslintrc from '../';
4 |
5 | const cli = new CLIEngine({
6 | useEslintrc: false,
7 | baseConfig: eslintrc,
8 | });
9 |
10 | function lint(text) {
11 | // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles
12 | // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext
13 | return cli.executeOnText(text).results[0];
14 | }
15 |
16 | function wrapComponent(body) {
17 | return `
18 | import React from 'react';
19 | export default class MyComponent extends React.Component {
20 | ${body}
21 | }
22 | `;
23 | }
24 |
25 | test('validate react prop order', t => {
26 | t.test('make sure our eslintrc has React linting dependencies', t => {
27 | t.plan(2);
28 | t.equal(eslintrc.parser, 'babel-eslint', 'uses babel-eslint');
29 | t.equal(eslintrc.plugins[0], 'react', 'uses eslint-plugin-react');
30 | });
31 |
32 | t.test('passes a good component', t => {
33 | t.plan(3);
34 | const result = lint(wrapComponent(`
35 | componentWillMount() { }
36 | componentDidMount() { }
37 | setFoo() { }
38 | getFoo() { }
39 | setBar() { }
40 | someMethod() { }
41 | renderDogs() { }
42 | render() { return ; }
43 | `));
44 |
45 | t.notOk(result.warningCount, 'no warnings');
46 | t.notOk(result.errorCount, 'no errors');
47 | t.deepEquals(result.messages, [], 'no messages in results');
48 | });
49 |
50 | t.test('order: when random method is first', t => {
51 | t.plan(2);
52 | const result = lint(wrapComponent(`
53 | someMethod() { }
54 | componentWillMount() { }
55 | componentDidMount() { }
56 | setFoo() { }
57 | getFoo() { }
58 | setBar() { }
59 | renderDogs() { }
60 | render() { return ; }
61 | `));
62 |
63 | t.ok(result.errorCount, 'fails');
64 | t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
65 | });
66 |
67 | t.test('order: when random method after lifecycle methods', t => {
68 | t.plan(2);
69 | const result = lint(wrapComponent(`
70 | componentWillMount() { }
71 | componentDidMount() { }
72 | someMethod() { }
73 | setFoo() { }
74 | getFoo() { }
75 | setBar() { }
76 | renderDogs() { }
77 | render() { return ; }
78 | `));
79 |
80 | t.ok(result.errorCount, 'fails');
81 | t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
82 | });
83 | });
84 |
--------------------------------------------------------------------------------
/react/README.md:
--------------------------------------------------------------------------------
1 | # Airbnb React/JSX Style Guide
2 |
3 | *A mostly reasonable approach to React and JSX*
4 |
5 | ## Table of Contents
6 |
7 | 1. [Basic Rules](#basic-rules)
8 | 1. [Naming](#naming)
9 | 1. [Declaration](#declaration)
10 | 1. [Alignment](#alignment)
11 | 1. [Quotes](#quotes)
12 | 1. [Spacing](#spacing)
13 | 1. [Props](#props)
14 | 1. [Parentheses](#parentheses)
15 | 1. [Tags](#tags)
16 | 1. [Methods](#methods)
17 | 1. [Ordering](#ordering)
18 |
19 | ## Basic Rules
20 |
21 | - Only include one React component per file.
22 | - Always use JSX syntax.
23 | - Do not use `React.createElement` unless you're initializing the app from a file that is not JSX.
24 |
25 | ## Class vs React.createClass
26 |
27 | - Use class extends React.Component unless you have a very good reason to use mixins.
28 |
29 | ```javascript
30 | // bad
31 | const Listing = React.createClass({
32 | render() {
33 | return ;
34 | }
35 | });
36 |
37 | // good
38 | class Listing extends React.Component {
39 | render() {
40 | return ;
41 | }
42 | }
43 | ```
44 |
45 | ## Naming
46 |
47 | - **Extensions**: Use `.jsx` extension for React components.
48 | - **Filename**: Use PascalCase for filenames. E.g., `ReservationCard.jsx`.
49 | - **Reference Naming**: Use PascalCase for React components and camelCase for their instances:
50 | ```javascript
51 | // bad
52 | const reservationCard = require('./ReservationCard');
53 |
54 | // good
55 | const ReservationCard = require('./ReservationCard');
56 |
57 | // bad
58 | const ReservationItem = ;
59 |
60 | // good
61 | const reservationItem = ;
62 | ```
63 |
64 | **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:
65 | ```javascript
66 | // bad
67 | const Footer = require('./Footer/Footer.jsx')
68 |
69 | // bad
70 | const Footer = require('./Footer/index.jsx')
71 |
72 | // good
73 | const Footer = require('./Footer')
74 | ```
75 |
76 |
77 | ## Declaration
78 | - Do not use displayName for naming components. Instead, name the component by reference.
79 |
80 | ```javascript
81 | // bad
82 | export default React.createClass({
83 | displayName: 'ReservationCard',
84 | // stuff goes here
85 | });
86 |
87 | // good
88 | class ReservationCard extends React.Component {
89 | }
90 |
91 | export default ReservationCard;
92 | ```
93 |
94 | ## Alignment
95 | - Follow these alignment styles for JS syntax
96 |
97 | ```javascript
98 | // bad
99 |
101 |
102 | // good
103 |
107 |
108 | // if props fit in one line then keep it on the same line
109 |
110 |
111 | // children get indented normally
112 |
116 |
117 |
118 | ```
119 |
120 | ## Quotes
121 | - Always use double quotes (`"`) for JSX attributes, but single quotes for all other JS.
122 | ```javascript
123 | // bad
124 |
125 |
126 | // good
127 |
128 |
129 | // bad
130 |
131 |
132 | // good
133 |
134 | ```
135 |
136 | ## Spacing
137 | - Always include a single space in your self-closing tag.
138 | ```javascript
139 | // bad
140 |
141 |
142 | // very bad
143 |
144 |
145 | // bad
146 |
148 |
149 | // good
150 |
151 | ```
152 |
153 | ## Props
154 | - Always use camelCase for prop names.
155 | ```javascript
156 | // bad
157 |
161 |
162 | // good
163 |
167 | ```
168 |
169 | ## Parentheses
170 | - Wrap JSX tags in parentheses when they span more than one line:
171 | ```javascript
172 | /// bad
173 | render() {
174 | return
175 |
176 | ;
177 | }
178 |
179 | // good
180 | render() {
181 | return (
182 |
183 |
184 |
185 | );
186 | }
187 |
188 | // good, when single line
189 | render() {
190 | const body = hello
;
191 | return {body};
192 | }
193 | ```
194 |
195 | ## Tags
196 | - Always self-close tags that have no children.
197 | ```javascript
198 | // bad
199 |
200 |
201 | // good
202 |
203 | ```
204 |
205 | - If your component has multi-line properties, close its tag on a new line.
206 | ```javascript
207 | // bad
208 |
211 |
212 | // good
213 |
217 | ```
218 |
219 | ## Methods
220 | - Do not use underscore prefix for internal methods of a React component.
221 | ```javascript
222 | // bad
223 | React.createClass({
224 | _onClickSubmit() {
225 | // do stuff
226 | }
227 |
228 | // other stuff
229 | });
230 |
231 | // good
232 | class extends React.Component {
233 | onClickSubmit() {
234 | // do stuff
235 | }
236 |
237 | // other stuff
238 | });
239 | ```
240 |
241 | ## Ordering
242 |
243 | - Ordering for class extends React.Component:
244 |
245 | 1. constructor
246 | 1. optional static methods
247 | 1. getChildContext
248 | 1. componentWillMount
249 | 1. componentDidMount
250 | 1. componentWillReceiveProps
251 | 1. shouldComponentUpdate
252 | 1. componentWillUpdate
253 | 1. componentDidUpdate
254 | 1. componentWillUnmount
255 | 1. *clickHandlers or eventHandlers* like onClickSubmit() or onChangeDescription()
256 | 1. *getter methods for render* like getSelectReason() or getFooterContent()
257 | 1. *Optional render methods* like renderNavigation() or renderProfilePicture()
258 | 1. render
259 |
260 | - How to define propTypes, defaultProps, contextTypes, etc...
261 |
262 | ```javascript
263 | import React, { Component, PropTypes } from 'react';
264 |
265 | export const propTypes = {
266 | id: PropTypes.number.isRequired,
267 | url: PropTypes.string.isRequired,
268 | text: PropTypes.string,
269 | };
270 |
271 | const defaultProps = {
272 | text: 'Hello World',
273 | };
274 |
275 | class Link extends Component {
276 | static methodsAreOk() {
277 | return true;
278 | }
279 |
280 | render() {
281 | return {this.props.text}
282 | }
283 | }
284 |
285 | Link.propTypes = propTypes;
286 | Link.defaultProps = defaultProps;
287 |
288 | export default Link;
289 | ```
290 |
291 | - Ordering for React.createClass:
292 |
293 | 1. displayName
294 | 1. propTypes
295 | 1. contextTypes
296 | 1. childContextTypes
297 | 1. mixins
298 | 1. statics
299 | 1. defaultProps
300 | 1. getDefaultProps
301 | 1. getInitialState
302 | 1. getChildContext
303 | 1. componentWillMount
304 | 1. componentDidMount
305 | 1. componentWillReceiveProps
306 | 1. shouldComponentUpdate
307 | 1. componentWillUpdate
308 | 1. componentDidUpdate
309 | 1. componentWillUnmount
310 | 1. *clickHandlers or eventHandlers* like onClickSubmit() or onChangeDescription()
311 | 1. *getter methods for render* like getSelectReason() or getFooterContent()
312 | 1. *Optional render methods* like renderNavigation() or renderProfilePicture()
313 | 1. render
314 |
315 | **[⬆ back to top](#table-of-contents)**
316 |
--------------------------------------------------------------------------------