eser 2.1.8 → 3.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/deno.json +6 -0
  2. package/deno.lock +41 -0
  3. package/hizli-api.js +90 -0
  4. package/main.js +5 -0
  5. package/mod.js +3 -0
  6. package/mod_test.js +5 -0
  7. package/package.json +8 -37
  8. package/.editorconfig +0 -14
  9. package/.gitattributes +0 -11
  10. package/.github/FUNDING.yml +0 -5
  11. package/LICENSE +0 -22
  12. package/README.md +0 -3794
  13. package/css-in-javascript/README.md +0 -432
  14. package/linters/.eslintrc +0 -6
  15. package/linters/.markdownlint.json +0 -154
  16. package/packages/eslint-config-eser/.editorconfig +0 -14
  17. package/packages/eslint-config-eser/.eslintrc +0 -3
  18. package/packages/eslint-config-eser/README.md +0 -19
  19. package/packages/eslint-config-eser/index.js +0 -20
  20. package/packages/eslint-config-eser/package.json +0 -49
  21. package/packages/eslint-config-eser/rules/best-practices.js +0 -381
  22. package/packages/eslint-config-eser/rules/errors.js +0 -146
  23. package/packages/eslint-config-eser/rules/es6.js +0 -203
  24. package/packages/eslint-config-eser/rules/imports.js +0 -291
  25. package/packages/eslint-config-eser/rules/node.js +0 -43
  26. package/packages/eslint-config-eser/rules/strict.js +0 -5
  27. package/packages/eslint-config-eser/rules/style.js +0 -597
  28. package/packages/eslint-config-eser/rules/variables.js +0 -53
  29. package/packages/eslint-config-eser-react/.editorconfig +0 -14
  30. package/packages/eslint-config-eser-react/.eslintrc +0 -3
  31. package/packages/eslint-config-eser-react/README.md +0 -19
  32. package/packages/eslint-config-eser-react/index.js +0 -11
  33. package/packages/eslint-config-eser-react/package.json +0 -59
  34. package/packages/eslint-config-eser-react/rules/react-a11y.js +0 -275
  35. package/packages/eslint-config-eser-react/rules/react-hooks.js +0 -21
  36. package/packages/eslint-config-eser-react/rules/react.js +0 -600
  37. package/react/README.md +0 -717
package/README.md DELETED
@@ -1,3794 +0,0 @@
1
- # [Eser: JavaScript Style Guide](https://github.com/eserozvataf/eser)
2
-
3
- *A mostly reasonable approach to JavaScript*
4
-
5
- [![npm version][npm-image]][npm-url]
6
- [![npm download][download-image]][npm-url]
7
- [![dependencies][dep-image]][dep-url]
8
- [![license][license-image]][license-url]
9
-
10
- Other Style Guides
11
-
12
- - [React](react/)
13
- - [CSS-in-JavaScript](css-in-javascript/)
14
-
15
- ## Table of Contents
16
-
17
- 1. [Types](#types)
18
- 1. [References](#references)
19
- 1. [Objects](#objects)
20
- 1. [Arrays](#arrays)
21
- 1. [Destructuring](#destructuring)
22
- 1. [Strings](#strings)
23
- 1. [Functions](#functions)
24
- 1. [Arrow Functions](#arrow-functions)
25
- 1. [Classes & Constructors](#classes--constructors)
26
- 1. [Modules](#modules)
27
- 1. [Iterators and Generators](#iterators-and-generators)
28
- 1. [Properties](#properties)
29
- 1. [Variables](#variables)
30
- 1. [Hoisting](#hoisting)
31
- 1. [Comparison Operators & Equality](#comparison-operators--equality)
32
- 1. [Blocks](#blocks)
33
- 1. [Control Statements](#control-statements)
34
- 1. [Comments](#comments)
35
- 1. [Whitespace](#whitespace)
36
- 1. [Commas](#commas)
37
- 1. [Semicolons](#semicolons)
38
- 1. [Type Casting & Coercion](#type-casting--coercion)
39
- 1. [Naming Conventions](#naming-conventions)
40
- 1. [Accessors](#accessors)
41
- 1. [Events](#events)
42
- 1. [jQuery](#jquery)
43
- 1. [ECMAScript 5 Compatibility](#ecmascript-5-compatibility)
44
- 1. [ECMAScript 6+ (ES 2015+) Styles](#ecmascript-6-es-2015-styles)
45
- 1. [Standard Library](#standard-library)
46
- 1. [Testing](#testing)
47
- 1. [Performance](#performance)
48
- 1. [Resources](#resources)
49
- 1. [Contributors](#contributors)
50
- 1. [License](#license)
51
- 1. [To Support](#to-support)
52
-
53
- ## Types
54
-
55
- <a name="types--primitives"></a><a name="1.1"></a>
56
- - [1.1](#types--primitives) **Primitives**: When you access a primitive type you work directly on its value.
57
-
58
- - `string`
59
- - `number`
60
- - `boolean`
61
- - `null`
62
- - `undefined`
63
- - `symbol`
64
-
65
- ```javascript
66
- const foo = 1;
67
- let bar = foo;
68
-
69
- bar = 9;
70
-
71
- console.log(foo, bar); // => 1, 9
72
- ```
73
-
74
- - Symbols cannot be faithfully polyfilled, so they should not be used when targeting browsers/environments that don’t support them natively.
75
-
76
- <a name="types--complex"></a><a name="1.2"></a>
77
- - [1.2](#types--complex) **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
- <a name="references--prefer-const"></a><a name="2.1"></a>
97
- - [2.1](#references--prefer-const) Use `const` for all of your references; avoid using `var`. eslint: [`prefer-const`](https://eslint.org/docs/rules/prefer-const.html), [`no-const-assign`](https://eslint.org/docs/rules/no-const-assign.html)
98
-
99
- > Why? This ensures that you can’t reassign your references, which can lead to bugs and difficult to comprehend code.
100
-
101
- ```javascript
102
- // bad
103
- var a = 1;
104
- var b = 2;
105
-
106
- // good
107
- const a = 1;
108
- const b = 2;
109
- ```
110
-
111
- <a name="references--disallow-var"></a><a name="2.2"></a>
112
- - [2.2](#references--disallow-var) If you must reassign references, use `let` instead of `var`. eslint: [`no-var`](https://eslint.org/docs/rules/no-var.html)
113
-
114
- > Why? `let` is block-scoped rather than function-scoped like `var`.
115
-
116
- ```javascript
117
- // bad
118
- var count = 1;
119
- if (true) {
120
- count += 1;
121
- }
122
-
123
- // good, use the let.
124
- let count = 1;
125
- if (true) {
126
- count += 1;
127
- }
128
- ```
129
-
130
- <a name="references--block-scope"></a><a name="2.3"></a>
131
- - [2.3](#references--block-scope) Note that both `let` and `const` are block-scoped.
132
-
133
- ```javascript
134
- // const and let only exist in the blocks they are defined in.
135
- {
136
- let a = 1;
137
- const b = 1;
138
- }
139
- console.log(a); // ReferenceError
140
- console.log(b); // ReferenceError
141
- ```
142
-
143
- **[⬆ back to top](#table-of-contents)**
144
-
145
- ## Objects
146
-
147
- <a name="objects--no-new"></a><a name="3.1"></a>
148
- - [3.1](#objects--no-new) Use the literal syntax for object creation. eslint: [`no-new-object`](https://eslint.org/docs/rules/no-new-object.html)
149
-
150
- ```javascript
151
- // bad
152
- const item = new Object();
153
-
154
- // good
155
- const item = {};
156
- ```
157
-
158
- <a name="es6-computed-properties"></a><a name="3.4"></a>
159
- - [3.2](#es6-computed-properties) Use computed property names when creating objects with dynamic property names.
160
-
161
- > Why? They allow you to define all the properties of an object in one place.
162
-
163
- ```javascript
164
-
165
- function getKey(k) {
166
- return `a key named ${k}`;
167
- }
168
-
169
- // bad
170
- const obj = {
171
- id: 5,
172
- name: 'San Francisco',
173
- };
174
- obj[getKey('enabled')] = true;
175
-
176
- // good
177
- const obj = {
178
- id: 5,
179
- name: 'San Francisco',
180
- [getKey('enabled')]: true,
181
- };
182
- ```
183
-
184
- <a name="es6-object-shorthand"></a><a name="3.5"></a>
185
- - [3.3](#es6-object-shorthand) Use object method shorthand. eslint: [`object-shorthand`](https://eslint.org/docs/rules/object-shorthand.html)
186
-
187
- ```javascript
188
- // bad
189
- const atom = {
190
- value: 1,
191
-
192
- addValue: function (value) {
193
- return atom.value + value;
194
- },
195
- };
196
-
197
- // good
198
- const atom = {
199
- value: 1,
200
-
201
- addValue(value) {
202
- return atom.value + value;
203
- },
204
- };
205
- ```
206
-
207
- <a name="es6-object-concise"></a><a name="3.6"></a>
208
- - [3.4](#es6-object-concise) Use property value shorthand. eslint: [`object-shorthand`](https://eslint.org/docs/rules/object-shorthand.html)
209
-
210
- > Why? It is shorter and descriptive.
211
-
212
- ```javascript
213
- const lukeSkywalker = 'Luke Skywalker';
214
-
215
- // bad
216
- const obj = {
217
- lukeSkywalker: lukeSkywalker,
218
- };
219
-
220
- // good
221
- const obj = {
222
- lukeSkywalker,
223
- };
224
- ```
225
-
226
- <a name="objects--grouped-shorthand"></a><a name="3.7"></a>
227
- - [3.5](#objects--grouped-shorthand) Group your shorthand properties at the beginning of your object declaration.
228
-
229
- > Why? It’s easier to tell which properties are using the shorthand.
230
-
231
- ```javascript
232
- const anakinSkywalker = 'Anakin Skywalker';
233
- const lukeSkywalker = 'Luke Skywalker';
234
-
235
- // bad
236
- const obj = {
237
- episodeOne: 1,
238
- twoJediWalkIntoACantina: 2,
239
- lukeSkywalker,
240
- episodeThree: 3,
241
- mayTheFourth: 4,
242
- anakinSkywalker,
243
- };
244
-
245
- // good
246
- const obj = {
247
- lukeSkywalker,
248
- anakinSkywalker,
249
- episodeOne: 1,
250
- twoJediWalkIntoACantina: 2,
251
- episodeThree: 3,
252
- mayTheFourth: 4,
253
- };
254
- ```
255
-
256
- <a name="objects--quoted-props"></a><a name="3.8"></a>
257
- - [3.6](#objects--quoted-props) Only quote properties that are invalid identifiers. eslint: [`quote-props`](https://eslint.org/docs/rules/quote-props.html)
258
-
259
- > Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.
260
-
261
- ```javascript
262
- // bad
263
- const bad = {
264
- 'foo': 3,
265
- 'bar': 4,
266
- 'data-blah': 5,
267
- };
268
-
269
- // good
270
- const good = {
271
- foo: 3,
272
- bar: 4,
273
- 'data-blah': 5,
274
- };
275
- ```
276
-
277
- <a name="objects--prototype-builtins"></a>
278
- - [3.7](#objects--prototype-builtins) Do not call `Object.prototype` methods directly, such as `hasOwnProperty`, `propertyIsEnumerable`, and `isPrototypeOf`. eslint: [`no-prototype-builtins`](https://eslint.org/docs/rules/no-prototype-builtins)
279
-
280
- > Why? These methods may be shadowed by properties on the object in question - consider `{ hasOwnProperty: false }` - or, the object may be a null object (`Object.create(null)`).
281
-
282
- ```javascript
283
- // bad
284
- console.log(object.hasOwnProperty(key));
285
-
286
- // good
287
- console.log(Object.prototype.hasOwnProperty.call(object, key));
288
-
289
- // best
290
- const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
291
- console.log(has.call(object, key));
292
- /* or */
293
- import has from 'has'; // https://www.npmjs.com/package/has
294
- console.log(has(object, key));
295
- ```
296
-
297
- <a name="objects--rest-spread"></a>
298
- - [3.8](#objects--rest-spread) Prefer the object spread operator over [`Object.assign`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) to shallow-copy objects. Use the object rest operator to get a new object with certain properties omitted.
299
-
300
- ```javascript
301
- // very bad
302
- const original = { a: 1, b: 2 };
303
- const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ
304
- delete copy.a; // so does this
305
-
306
- // bad
307
- const original = { a: 1, b: 2 };
308
- const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }
309
-
310
- // good
311
- const original = { a: 1, b: 2 };
312
- const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }
313
-
314
- const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
315
- ```
316
-
317
- **[⬆ back to top](#table-of-contents)**
318
-
319
- ## Arrays
320
-
321
- <a name="arrays--literals"></a><a name="4.1"></a>
322
- - [4.1](#arrays--literals) Use the literal syntax for array creation. eslint: [`no-array-constructor`](https://eslint.org/docs/rules/no-array-constructor.html)
323
-
324
- ```javascript
325
- // bad
326
- const items = new Array();
327
-
328
- // good
329
- const items = [];
330
- ```
331
-
332
- <a name="arrays--push"></a><a name="4.2"></a>
333
- - [4.2](#arrays--push) Use [Array#push](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push) instead of direct assignment to add items to an array.
334
-
335
- ```javascript
336
- const someStack = [];
337
-
338
- // bad
339
- someStack[someStack.length] = 'abracadabra';
340
-
341
- // good
342
- someStack.push('abracadabra');
343
- ```
344
-
345
- <a name="es6-array-spreads"></a><a name="4.3"></a>
346
- - [4.3](#es6-array-spreads) Use array spreads `...` to copy arrays.
347
-
348
- ```javascript
349
- // bad
350
- const len = items.length;
351
- const itemsCopy = [];
352
- let i;
353
-
354
- for (i = 0; i < len; i += 1) {
355
- itemsCopy[i] = items[i];
356
- }
357
-
358
- // good
359
- const itemsCopy = [...items];
360
- ```
361
-
362
- <a name="arrays--from"></a>
363
- <a name="arrays--from-iterable"></a><a name="4.4"></a>
364
- - [4.4](#arrays--from-iterable) To convert an iterable object to an array, use spreads `...` instead of [`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from).
365
-
366
- ```javascript
367
- const foo = document.querySelectorAll('.foo');
368
-
369
- // good
370
- const nodes = Array.from(foo);
371
-
372
- // best
373
- const nodes = [...foo];
374
- ```
375
-
376
- <a name="arrays--from-array-like"></a>
377
- - [4.5](#arrays--from-array-like) Use [`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from) for converting an array-like object to an array.
378
-
379
- ```javascript
380
- const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };
381
-
382
- // bad
383
- const arr = Array.prototype.slice.call(arrLike);
384
-
385
- // good
386
- const arr = Array.from(arrLike);
387
- ```
388
-
389
- <a name="arrays--mapping"></a>
390
- - [4.6](#arrays--mapping) Use [`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from) instead of spread `...` for mapping over iterables, because it avoids creating an intermediate array.
391
-
392
- ```javascript
393
- // bad
394
- const baz = [...foo].map(bar);
395
-
396
- // good
397
- const baz = Array.from(foo, bar);
398
- ```
399
-
400
- <a name="arrays--callback-return"></a><a name="4.5"></a>
401
- - [4.7](#arrays--callback-return) Use return statements in array method callbacks. It’s ok to omit the return if the function body consists of a single statement returning an expression without side effects, following [8.2](#arrows--implicit-return). eslint: [`array-callback-return`](https://eslint.org/docs/rules/array-callback-return)
402
-
403
- ```javascript
404
- // good
405
- [1, 2, 3].map((x) => {
406
- const y = x + 1;
407
- return x * y;
408
- });
409
-
410
- // good
411
- [1, 2, 3].map((x) => x + 1);
412
-
413
- // bad - no returned value means `acc` becomes undefined after the first iteration
414
- [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
415
- const flatten = acc.concat(item);
416
- });
417
-
418
- // good
419
- [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
420
- const flatten = acc.concat(item);
421
- return flatten;
422
- });
423
-
424
- // bad
425
- inbox.filter((msg) => {
426
- const { subject, author } = msg;
427
- if (subject === 'Mockingbird') {
428
- return author === 'Harper Lee';
429
- } else {
430
- return false;
431
- }
432
- });
433
-
434
- // good
435
- inbox.filter((msg) => {
436
- const { subject, author } = msg;
437
- if (subject === 'Mockingbird') {
438
- return author === 'Harper Lee';
439
- }
440
-
441
- return false;
442
- });
443
- ```
444
-
445
- <a name="arrays--bracket-newline"></a>
446
- - [4.8](#arrays--bracket-newline) Use line breaks after open and before close array brackets if an array has multiple lines
447
-
448
- ```javascript
449
- // bad
450
- const arr = [
451
- [0, 1], [2, 3], [4, 5],
452
- ];
453
-
454
- const objectInArray = [{
455
- id: 1,
456
- }, {
457
- id: 2,
458
- }];
459
-
460
- const numberInArray = [
461
- 1, 2,
462
- ];
463
-
464
- // good
465
- const arr = [[0, 1], [2, 3], [4, 5]];
466
-
467
- const objectInArray = [
468
- {
469
- id: 1,
470
- },
471
- {
472
- id: 2,
473
- },
474
- ];
475
-
476
- const numberInArray = [
477
- 1,
478
- 2,
479
- ];
480
- ```
481
-
482
- **[⬆ back to top](#table-of-contents)**
483
-
484
- ## Destructuring
485
-
486
- <a name="destructuring--object"></a><a name="5.1"></a>
487
- - [5.1](#destructuring--object) Use object destructuring when accessing and using multiple properties of an object. eslint: [`prefer-destructuring`](https://eslint.org/docs/rules/prefer-destructuring)
488
-
489
- > Why? Destructuring saves you from creating temporary references for those properties.
490
-
491
- ```javascript
492
- // bad
493
- function getFullName(user) {
494
- const firstName = user.firstName;
495
- const lastName = user.lastName;
496
-
497
- return `${firstName} ${lastName}`;
498
- }
499
-
500
- // good
501
- function getFullName(user) {
502
- const { firstName, lastName } = user;
503
- return `${firstName} ${lastName}`;
504
- }
505
-
506
- // best
507
- function getFullName({ firstName, lastName }) {
508
- return `${firstName} ${lastName}`;
509
- }
510
- ```
511
-
512
- <a name="destructuring--array"></a><a name="5.2"></a>
513
- - [5.2](#destructuring--array) Use array destructuring. eslint: [`prefer-destructuring`](https://eslint.org/docs/rules/prefer-destructuring)
514
-
515
- ```javascript
516
- const arr = [1, 2, 3, 4];
517
-
518
- // bad
519
- const first = arr[0];
520
- const second = arr[1];
521
-
522
- // good
523
- const [first, second] = arr;
524
- ```
525
-
526
- <a name="destructuring--object-over-array"></a><a name="5.3"></a>
527
- - [5.3](#destructuring--object-over-array) Use object destructuring for multiple return values, not array destructuring.
528
-
529
- > Why? You can add new properties over time or change the order of things without breaking call sites.
530
-
531
- ```javascript
532
- // bad
533
- function processInput(input) {
534
- // then a miracle occurs
535
- return [left, right, top, bottom];
536
- }
537
-
538
- // the caller needs to think about the order of return data
539
- const [left, __, top] = processInput(input);
540
-
541
- // good
542
- function processInput(input) {
543
- // then a miracle occurs
544
- return { left, right, top, bottom };
545
- }
546
-
547
- // the caller selects only the data they need
548
- const { left, top } = processInput(input);
549
- ```
550
-
551
- **[⬆ back to top](#table-of-contents)**
552
-
553
- ## Strings
554
-
555
- <a name="strings--quotes"></a><a name="6.1"></a>
556
- - [6.1](#strings--quotes) Use single quotes `''` for strings. eslint: [`quotes`](https://eslint.org/docs/rules/quotes.html)
557
-
558
- ```javascript
559
- // bad
560
- const name = "Capt. Janeway";
561
-
562
- // bad - template literals should contain interpolation or newlines
563
- const name = `Capt. Janeway`;
564
-
565
- // good
566
- const name = 'Capt. Janeway';
567
- ```
568
-
569
- <a name="strings--line-length"></a><a name="6.2"></a>
570
- - [6.2](#strings--line-length) Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation.
571
-
572
- > Why? Broken strings are painful to work with and make code less searchable.
573
-
574
- ```javascript
575
- // bad
576
- const errorMessage = 'This is a super long error that was thrown because \
577
- of Batman. When you stop to think about how Batman had anything to do \
578
- with this, you would get nowhere \
579
- fast.';
580
-
581
- // bad
582
- const errorMessage = 'This is a super long error that was thrown because ' +
583
- 'of Batman. When you stop to think about how Batman had anything to do ' +
584
- 'with this, you would get nowhere fast.';
585
-
586
- // good
587
- 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.';
588
- ```
589
-
590
- <a name="es6-template-literals"></a><a name="6.4"></a>
591
- - [6.3](#es6-template-literals) When programmatically building up strings, use template strings instead of concatenation. eslint: [`prefer-template`](https://eslint.org/docs/rules/prefer-template.html) [`template-curly-spacing`](https://eslint.org/docs/rules/template-curly-spacing)
592
-
593
- > Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.
594
-
595
- ```javascript
596
- // bad
597
- function sayHi(name) {
598
- return 'How are you, ' + name + '?';
599
- }
600
-
601
- // bad
602
- function sayHi(name) {
603
- return ['How are you, ', name, '?'].join();
604
- }
605
-
606
- // bad
607
- function sayHi(name) {
608
- return `How are you, ${ name }?`;
609
- }
610
-
611
- // good
612
- function sayHi(name) {
613
- return `How are you, ${name}?`;
614
- }
615
- ```
616
-
617
- <a name="strings--eval"></a><a name="6.5"></a>
618
- - [6.4](#strings--eval) Never use `eval()` on a string, it opens too many vulnerabilities. eslint: [`no-eval`](https://eslint.org/docs/rules/no-eval)
619
-
620
- <a name="strings--escaping"></a>
621
- - [6.5](#strings--escaping) Do not unnecessarily escape characters in strings. eslint: [`no-useless-escape`](https://eslint.org/docs/rules/no-useless-escape)
622
-
623
- > Why? Backslashes harm readability, thus they should only be present when necessary.
624
-
625
- ```javascript
626
- // bad
627
- const foo = '\'this\' \i\s \"quoted\"';
628
-
629
- // good
630
- const foo = '\'this\' is "quoted"';
631
- const foo = `my name is '${name}'`;
632
- ```
633
-
634
- **[⬆ back to top](#table-of-contents)**
635
-
636
- ## Functions
637
-
638
- <a name="functions--declarations"></a><a name="7.1"></a>
639
- - [7.1](#functions--declarations) Use named function expressions instead of function declarations. eslint: [`func-style`](https://eslint.org/docs/rules/func-style)
640
-
641
- > Why? Function declarations are hoisted, which means that it’s easy - too easy - to reference the function before it is defined in the file. This harms readability and maintainability. If you find that a function’s definition is large or complex enough that it is interfering with understanding the rest of the file, then perhaps it’s time to extract it to its own module! Don’t forget to explicitly name the expression, regardless of whether or not the name is inferred from the containing variable (which is often the case in modern browsers or when using compilers such as Babel). This eliminates any assumptions made about the Error’s call stack. ([Discussion](https://github.com/airbnb/javascript/issues/794))
642
-
643
- ```javascript
644
- // bad
645
- function foo() {
646
- // ...
647
- }
648
-
649
- // bad
650
- const foo = function () {
651
- // ...
652
- };
653
-
654
- // good
655
- // lexical name distinguished from the variable-referenced invocation(s)
656
- const short = function longUniqueMoreDescriptiveLexicalFoo() {
657
- // ...
658
- };
659
- ```
660
-
661
- <a name="functions--iife"></a><a name="7.2"></a>
662
- - [7.2](#functions--iife) Wrap immediately invoked function expressions in parentheses. eslint: [`wrap-iife`](https://eslint.org/docs/rules/wrap-iife.html)
663
-
664
- > Why? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this. Note that in a world with modules everywhere, you almost never need an IIFE.
665
-
666
- ```javascript
667
- // immediately-invoked function expression (IIFE)
668
- (function () {
669
- console.log('Welcome to the Internet. Please follow me.');
670
- }());
671
- ```
672
-
673
- <a name="functions--in-blocks"></a><a name="7.3"></a>
674
- - [7.3](#functions--in-blocks) Never declare a function in a non-function block (`if`, `while`, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears. eslint: [`no-loop-func`](https://eslint.org/docs/rules/no-loop-func.html)
675
-
676
- <a name="functions--note-on-blocks"></a><a name="7.4"></a>
677
- - [7.4](#functions--note-on-blocks) **Note:** ECMA-262 defines a `block` as a list of statements. A function declaration is not a statement.
678
-
679
- ```javascript
680
- // bad
681
- if (currentUser) {
682
- function test() {
683
- console.log('Nope.');
684
- }
685
- }
686
-
687
- // good
688
- let test;
689
- if (currentUser) {
690
- test = () => {
691
- console.log('Yup.');
692
- };
693
- }
694
- ```
695
-
696
- <a name="functions--arguments-shadow"></a><a name="7.5"></a>
697
- - [7.5](#functions--arguments-shadow) Never name a parameter `arguments`. This will take precedence over the `arguments` object that is given to every function scope.
698
-
699
- ```javascript
700
- // bad
701
- function foo(name, options, arguments) {
702
- // ...
703
- }
704
-
705
- // good
706
- function foo(name, options, args) {
707
- // ...
708
- }
709
- ```
710
-
711
- <a name="es6-rest"></a><a name="7.6"></a>
712
- - [7.6](#es6-rest) Never use `arguments`, opt to use rest syntax `...` instead. eslint: [`prefer-rest-params`](https://eslint.org/docs/rules/prefer-rest-params)
713
-
714
- > Why? `...` is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like like `arguments`.
715
-
716
- ```javascript
717
- // bad
718
- function concatenateAll() {
719
- const args = Array.prototype.slice.call(arguments);
720
- return args.join('');
721
- }
722
-
723
- // good
724
- function concatenateAll(...args) {
725
- return args.join('');
726
- }
727
- ```
728
-
729
- <a name="es6-default-parameters"></a><a name="7.7"></a>
730
- - [7.7](#es6-default-parameters) Use default parameter syntax rather than mutating function arguments.
731
-
732
- ```javascript
733
- // really bad
734
- function handleThings(opts) {
735
- // No! We shouldn’t mutate function arguments.
736
- // Double bad: if opts is falsy it'll be set to an object which may
737
- // be what you want but it can introduce subtle bugs.
738
- opts = opts || {};
739
- // ...
740
- }
741
-
742
- // still bad
743
- function handleThings(opts) {
744
- if (opts === void 0) {
745
- opts = {};
746
- }
747
- // ...
748
- }
749
-
750
- // good
751
- function handleThings(opts = {}) {
752
- // ...
753
- }
754
- ```
755
-
756
- <a name="functions--default-side-effects"></a><a name="7.8"></a>
757
- - [7.8](#functions--default-side-effects) Avoid side effects with default parameters.
758
-
759
- > Why? They are confusing to reason about.
760
-
761
- ```javascript
762
- var b = 1;
763
- // bad
764
- function count(a = b++) {
765
- console.log(a);
766
- }
767
- count(); // 1
768
- count(); // 2
769
- count(3); // 3
770
- count(); // 3
771
- ```
772
-
773
- <a name="functions--defaults-last"></a><a name="7.9"></a>
774
- - [7.9](#functions--defaults-last) Always put default parameters last.
775
-
776
- ```javascript
777
- // bad
778
- function handleThings(opts = {}, name) {
779
- // ...
780
- }
781
-
782
- // good
783
- function handleThings(name, opts = {}) {
784
- // ...
785
- }
786
- ```
787
-
788
- <a name="functions--constructor"></a><a name="7.10"></a>
789
- - [7.10](#functions--constructor) Never use the Function constructor to create a new function. eslint: [`no-new-func`](https://eslint.org/docs/rules/no-new-func)
790
-
791
- > Why? Creating a function in this way evaluates a string similarly to `eval()`, which opens vulnerabilities.
792
-
793
- ```javascript
794
- // bad
795
- var add = new Function('a', 'b', 'return a + b');
796
-
797
- // still bad
798
- var subtract = Function('a', 'b', 'return a - b');
799
- ```
800
-
801
- <a name="functions--signature-spacing"></a><a name="7.11"></a>
802
- - [7.11](#functions--signature-spacing) Spacing in a function signature. eslint: [`space-before-function-paren`](https://eslint.org/docs/rules/space-before-function-paren) [`space-before-blocks`](https://eslint.org/docs/rules/space-before-blocks)
803
-
804
- > Why? Consistency is good, and you shouldn’t have to add or remove a space when adding or removing a name.
805
-
806
- ```javascript
807
- // bad
808
- const f = function(){};
809
- const g = function (){};
810
- const h = function() {};
811
-
812
- // good
813
- const x = function () {};
814
- const y = function a() {};
815
- ```
816
-
817
- <a name="functions--mutate-params"></a><a name="7.12"></a>
818
- - [7.12](#functions--mutate-params) Never mutate parameters. eslint: [`no-param-reassign`](https://eslint.org/docs/rules/no-param-reassign.html)
819
-
820
- > Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller.
821
-
822
- ```javascript
823
- // bad
824
- function f1(obj) {
825
- obj.key = 1;
826
- }
827
-
828
- // good
829
- function f2(obj) {
830
- const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;
831
- }
832
- ```
833
-
834
- <a name="functions--reassign-params"></a><a name="7.13"></a>
835
- - [7.13](#functions--reassign-params) Never reassign parameters. eslint: [`no-param-reassign`](https://eslint.org/docs/rules/no-param-reassign.html)
836
-
837
- > Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the `arguments` object. It can also cause optimization issues, especially in V8.
838
-
839
- ```javascript
840
- // bad
841
- function f1(a) {
842
- a = 1;
843
- // ...
844
- }
845
-
846
- function f2(a) {
847
- if (!a) { a = 1; }
848
- // ...
849
- }
850
-
851
- // good
852
- function f3(a) {
853
- const b = a || 1;
854
- // ...
855
- }
856
-
857
- function f4(a = 1) {
858
- // ...
859
- }
860
- ```
861
-
862
- <a name="functions--spread-vs-apply"></a><a name="7.14"></a>
863
- - [7.14](#functions--spread-vs-apply) Prefer the use of the spread operator `...` to call variadic functions. eslint: [`prefer-spread`](https://eslint.org/docs/rules/prefer-spread)
864
-
865
- > Why? It’s cleaner, you don’t need to supply a context, and you can not easily compose `new` with `apply`.
866
-
867
- ```javascript
868
- // bad
869
- const x = [1, 2, 3, 4, 5];
870
- console.log.apply(console, x);
871
-
872
- // good
873
- const x = [1, 2, 3, 4, 5];
874
- console.log(...x);
875
-
876
- // bad
877
- new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5]));
878
-
879
- // good
880
- new Date(...[2016, 8, 5]);
881
- ```
882
-
883
- <a name="functions--signature-invocation-indentation"></a>
884
- - [7.15](#functions--signature-invocation-indentation) Functions with multiline signatures, or invocations, should be indented just like every other multiline list in this guide: with each item on a line by itself, with a trailing comma on the last item. eslint: [`function-paren-newline`](https://eslint.org/docs/rules/function-paren-newline)
885
-
886
- ```javascript
887
- // bad
888
- function foo(bar,
889
- baz,
890
- quux) {
891
- // ...
892
- }
893
-
894
- // good
895
- function foo(
896
- bar,
897
- baz,
898
- quux,
899
- ) {
900
- // ...
901
- }
902
-
903
- // bad
904
- console.log(foo,
905
- bar,
906
- baz);
907
-
908
- // good
909
- console.log(
910
- foo,
911
- bar,
912
- baz,
913
- );
914
- ```
915
-
916
- **[⬆ back to top](#table-of-contents)**
917
-
918
- ## Arrow Functions
919
-
920
- <a name="arrows--use-them"></a><a name="8.1"></a>
921
- - [8.1](#arrows--use-them) When you must use an anonymous function (as when passing an inline callback), use arrow function notation. eslint: [`prefer-arrow-callback`](https://eslint.org/docs/rules/prefer-arrow-callback.html), [`arrow-spacing`](https://eslint.org/docs/rules/arrow-spacing.html)
922
-
923
- > 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.
924
-
925
- > Why not? If you have a fairly complicated function, you might move that logic out into its own named function expression.
926
-
927
- ```javascript
928
- // bad
929
- [1, 2, 3].map(function (x) {
930
- const y = x + 1;
931
- return x * y;
932
- });
933
-
934
- // good
935
- [1, 2, 3].map((x) => {
936
- const y = x + 1;
937
- return x * y;
938
- });
939
- ```
940
-
941
- <a name="arrows--implicit-return"></a><a name="8.2"></a>
942
- - [8.2](#arrows--implicit-return) If the function body consists of a single statement returning an [expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions) without side effects, omit the braces and use the implicit return. Otherwise, keep the braces and use a `return` statement. eslint: [`arrow-parens`](https://eslint.org/docs/rules/arrow-parens.html), [`arrow-body-style`](https://eslint.org/docs/rules/arrow-body-style.html)
943
-
944
- > Why? Syntactic sugar. It reads well when multiple functions are chained together.
945
-
946
- ```javascript
947
- // bad
948
- [1, 2, 3].map((number) => {
949
- const nextNumber = number + 1;
950
- `A string containing the ${nextNumber}.`;
951
- });
952
-
953
- // good
954
- [1, 2, 3].map((number) => `A string containing the ${number + 1}.`);
955
-
956
- // good
957
- [1, 2, 3].map((number) => {
958
- const nextNumber = number + 1;
959
- return `A string containing the ${nextNumber}.`;
960
- });
961
-
962
- // good
963
- [1, 2, 3].map((number, index) => ({
964
- [index]: number,
965
- }));
966
-
967
- // No implicit return with side effects
968
- function foo(callback) {
969
- const val = callback();
970
- if (val === true) {
971
- // Do something if callback returns true
972
- }
973
- }
974
-
975
- let bool = false;
976
-
977
- // bad
978
- foo(() => bool = true);
979
-
980
- // good
981
- foo(() => {
982
- bool = true;
983
- });
984
- ```
985
-
986
- <a name="arrows--paren-wrap"></a><a name="8.3"></a>
987
- - [8.3](#arrows--paren-wrap) In case the expression spans over multiple lines, wrap it in parentheses for better readability.
988
-
989
- > Why? It shows clearly where the function starts and ends.
990
-
991
- ```javascript
992
- // bad
993
- ['get', 'post', 'put'].map((httpMethod) => Object.prototype.hasOwnProperty.call(
994
- httpMagicObjectWithAVeryLongName,
995
- httpMethod,
996
- )
997
- );
998
-
999
- // good
1000
- ['get', 'post', 'put'].map((httpMethod) => (
1001
- Object.prototype.hasOwnProperty.call(
1002
- httpMagicObjectWithAVeryLongName,
1003
- httpMethod,
1004
- )
1005
- ));
1006
- ```
1007
-
1008
- <a name="arrows--one-arg-parens"></a><a name="8.4"></a>
1009
- - [8.4](#arrows--one-arg-parens) Always include parentheses around arguments for clarity and consistency. eslint: [`arrow-parens`](https://eslint.org/docs/rules/arrow-parens.html)
1010
-
1011
- > Why? Minimizes diff churn when adding or removing arguments.
1012
-
1013
- ```javascript
1014
- // bad
1015
- [1, 2, 3].map(x => x * x);
1016
-
1017
- // good
1018
- [1, 2, 3].map((x) => x * x);
1019
-
1020
- // bad
1021
- [1, 2, 3].map(number => (
1022
- `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`
1023
- ));
1024
-
1025
- // good
1026
- [1, 2, 3].map((number) => (
1027
- `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`
1028
- ));
1029
-
1030
- // bad
1031
- [1, 2, 3].map(x => {
1032
- const y = x + 1;
1033
- return x * y;
1034
- });
1035
-
1036
- // good
1037
- [1, 2, 3].map((x) => {
1038
- const y = x + 1;
1039
- return x * y;
1040
- });
1041
- ```
1042
-
1043
- <a name="arrows--confusing"></a><a name="8.5"></a>
1044
- - [8.5](#arrows--confusing) Avoid confusing arrow function syntax (`=>`) with comparison operators (`<=`, `>=`). eslint: [`no-confusing-arrow`](https://eslint.org/docs/rules/no-confusing-arrow)
1045
-
1046
- ```javascript
1047
- // bad
1048
- const itemHeight = (item) => item.height <= 256 ? item.largeSize : item.smallSize;
1049
-
1050
- // bad
1051
- const itemHeight = (item) => item.height >= 256 ? item.largeSize : item.smallSize;
1052
-
1053
- // good
1054
- const itemHeight = (item) => (item.height <= 256 ? item.largeSize : item.smallSize);
1055
-
1056
- // good
1057
- const itemHeight = (item) => {
1058
- const { height, largeSize, smallSize } = item;
1059
- return height <= 256 ? largeSize : smallSize;
1060
- };
1061
- ```
1062
-
1063
- <a name="whitespace--implicit-arrow-linebreak"></a>
1064
- - [8.6](#whitespace--implicit-arrow-linebreak) Enforce the location of arrow function bodies with implicit returns. eslint: [`implicit-arrow-linebreak`](https://eslint.org/docs/rules/implicit-arrow-linebreak)
1065
-
1066
- ```javascript
1067
- // bad
1068
- (foo) =>
1069
- bar;
1070
-
1071
- (foo) =>
1072
- (bar);
1073
-
1074
- // good
1075
- (foo) => bar;
1076
- (foo) => (bar);
1077
- (foo) => (
1078
- bar
1079
- )
1080
- ```
1081
-
1082
- **[⬆ back to top](#table-of-contents)**
1083
-
1084
- ## Classes & Constructors
1085
-
1086
- <a name="constructors--use-class"></a><a name="9.1"></a>
1087
- - [9.1](#constructors--use-class) Always use `class`. Avoid manipulating `prototype` directly.
1088
-
1089
- > Why? `class` syntax is more concise and easier to reason about.
1090
-
1091
- ```javascript
1092
- // bad
1093
- function Queue(contents = []) {
1094
- this.queue = [...contents];
1095
- }
1096
- Queue.prototype.pop = function () {
1097
- const value = this.queue[0];
1098
- this.queue.splice(0, 1);
1099
- return value;
1100
- };
1101
-
1102
- // good
1103
- class Queue {
1104
- constructor(contents = []) {
1105
- this.queue = [...contents];
1106
- }
1107
- pop() {
1108
- const value = this.queue[0];
1109
- this.queue.splice(0, 1);
1110
- return value;
1111
- }
1112
- }
1113
- ```
1114
-
1115
- <a name="constructors--extends"></a><a name="9.2"></a>
1116
- - [9.2](#constructors--extends) Use `extends` for inheritance.
1117
-
1118
- > Why? It is a built-in way to inherit prototype functionality without breaking `instanceof`.
1119
-
1120
- ```javascript
1121
- // bad
1122
- const inherits = require('inherits');
1123
- function PeekableQueue(contents) {
1124
- Queue.apply(this, contents);
1125
- }
1126
- inherits(PeekableQueue, Queue);
1127
- PeekableQueue.prototype.peek = function () {
1128
- return this.queue[0];
1129
- };
1130
-
1131
- // good
1132
- class PeekableQueue extends Queue {
1133
- peek() {
1134
- return this.queue[0];
1135
- }
1136
- }
1137
- ```
1138
-
1139
- <a name="constructors--chaining"></a><a name="9.3"></a>
1140
- - [9.3](#constructors--chaining) Methods can return `this` to help with method chaining.
1141
-
1142
- ```javascript
1143
- // bad
1144
- Jedi.prototype.jump = function () {
1145
- this.jumping = true;
1146
- return true;
1147
- };
1148
-
1149
- Jedi.prototype.setHeight = function (height) {
1150
- this.height = height;
1151
- };
1152
-
1153
- const luke = new Jedi();
1154
- luke.jump(); // => true
1155
- luke.setHeight(20); // => undefined
1156
-
1157
- // good
1158
- class Jedi {
1159
- jump() {
1160
- this.jumping = true;
1161
- return this;
1162
- }
1163
-
1164
- setHeight(height) {
1165
- this.height = height;
1166
- return this;
1167
- }
1168
- }
1169
-
1170
- const luke = new Jedi();
1171
-
1172
- luke.jump()
1173
- .setHeight(20);
1174
- ```
1175
-
1176
- <a name="constructors--tostring"></a><a name="9.4"></a>
1177
- - [9.4](#constructors--tostring) It’s okay to write a custom `toString()` method, just make sure it works successfully and causes no side effects.
1178
-
1179
- ```javascript
1180
- class Jedi {
1181
- constructor(options = {}) {
1182
- this.name = options.name || 'no name';
1183
- }
1184
-
1185
- getName() {
1186
- return this.name;
1187
- }
1188
-
1189
- toString() {
1190
- return `Jedi - ${this.getName()}`;
1191
- }
1192
- }
1193
- ```
1194
-
1195
- <a name="constructors--no-useless"></a><a name="9.5"></a>
1196
- - [9.5](#constructors--no-useless) Classes have a default constructor if one is not specified. An empty constructor function or one that just delegates to a parent class is unnecessary. eslint: [`no-useless-constructor`](https://eslint.org/docs/rules/no-useless-constructor)
1197
-
1198
- ```javascript
1199
- // bad
1200
- class Jedi {
1201
- constructor() {}
1202
-
1203
- getName() {
1204
- return this.name;
1205
- }
1206
- }
1207
-
1208
- // bad
1209
- class Rey extends Jedi {
1210
- constructor(...args) {
1211
- super(...args);
1212
- }
1213
- }
1214
-
1215
- // good
1216
- class Rey extends Jedi {
1217
- constructor(...args) {
1218
- super(...args);
1219
- this.name = 'Rey';
1220
- }
1221
- }
1222
- ```
1223
-
1224
- <a name="classes--no-duplicate-members"></a>
1225
- - [9.6](#classes--no-duplicate-members) Avoid duplicate class members. eslint: [`no-dupe-class-members`](https://eslint.org/docs/rules/no-dupe-class-members)
1226
-
1227
- > Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug.
1228
-
1229
- ```javascript
1230
- // bad
1231
- class Foo {
1232
- bar() { return 1; }
1233
- bar() { return 2; }
1234
- }
1235
-
1236
- // good
1237
- class Foo {
1238
- bar() { return 1; }
1239
- }
1240
-
1241
- // good
1242
- class Foo {
1243
- bar() { return 2; }
1244
- }
1245
- ```
1246
-
1247
- **[⬆ back to top](#table-of-contents)**
1248
-
1249
- ## Modules
1250
-
1251
- <a name="modules--use-them"></a><a name="10.1"></a>
1252
- - [10.1](#modules--use-them) Always use modules (`import`/`export`) over a non-standard module system. You can always transpile to your preferred module system.
1253
-
1254
- > Why? Modules are the future, let’s start using the future now.
1255
-
1256
- ```javascript
1257
- // bad
1258
- const AirbnbStyleGuide = require('./AirbnbStyleGuide');
1259
- module.exports = AirbnbStyleGuide.es6;
1260
-
1261
- // ok
1262
- import AirbnbStyleGuide from './AirbnbStyleGuide';
1263
- export default AirbnbStyleGuide.es6;
1264
-
1265
- // best
1266
- import { es6 } from './AirbnbStyleGuide';
1267
- export default es6;
1268
- ```
1269
-
1270
- <a name="modules--no-wildcard"></a><a name="10.2"></a>
1271
- - [10.2](#modules--no-wildcard) Do not use wildcard imports.
1272
-
1273
- > Why? This makes sure you have a single default export.
1274
-
1275
- ```javascript
1276
- // bad
1277
- import * as AirbnbStyleGuide from './AirbnbStyleGuide';
1278
-
1279
- // good
1280
- import AirbnbStyleGuide from './AirbnbStyleGuide';
1281
- ```
1282
-
1283
- <a name="modules--no-export-from-import"></a><a name="10.3"></a>
1284
- - [10.3](#modules--no-export-from-import) And do not export directly from an import.
1285
-
1286
- > Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent.
1287
-
1288
- ```javascript
1289
- // bad
1290
- // filename es6.js
1291
- export { es6 as default } from './AirbnbStyleGuide';
1292
-
1293
- // good
1294
- // filename es6.js
1295
- import { es6 } from './AirbnbStyleGuide';
1296
- export default es6;
1297
- ```
1298
-
1299
- <a name="modules--no-duplicate-imports"></a>
1300
- - [10.4](#modules--no-duplicate-imports) Only import from a path in one place.
1301
- eslint: [`no-duplicate-imports`](https://eslint.org/docs/rules/no-duplicate-imports)
1302
- > Why? Having multiple lines that import from the same path can make code harder to maintain.
1303
-
1304
- ```javascript
1305
- // bad
1306
- import foo from 'foo';
1307
- // … some other imports … //
1308
- import { named1, named2 } from 'foo';
1309
-
1310
- // good
1311
- import foo, { named1, named2 } from 'foo';
1312
-
1313
- // good
1314
- import foo, {
1315
- named1,
1316
- named2,
1317
- } from 'foo';
1318
- ```
1319
-
1320
- <a name="modules--no-mutable-exports"></a>
1321
- - [10.5](#modules--no-mutable-exports) Do not export mutable bindings.
1322
- eslint: [`import/no-mutable-exports`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md)
1323
- > Why? Mutation should be avoided in general, but in particular when exporting mutable bindings. While this technique may be needed for some special cases, in general, only constant references should be exported.
1324
-
1325
- ```javascript
1326
- // bad
1327
- let foo = 3;
1328
- export { foo };
1329
-
1330
- // good
1331
- const foo = 3;
1332
- export { foo };
1333
- ```
1334
-
1335
- <a name="modules--prefer-default-export"></a>
1336
- - [10.6](#modules--prefer-default-export) In modules with a single export, prefer default export over named export.
1337
- eslint: [`import/prefer-default-export`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md)
1338
- > Why? To encourage more files that only ever export one thing, which is better for readability and maintainability.
1339
-
1340
- ```javascript
1341
- // bad
1342
- export function foo() {}
1343
-
1344
- // good
1345
- export default function foo() {}
1346
- ```
1347
-
1348
- <a name="modules--imports-first"></a>
1349
- - [10.7](#modules--imports-first) Put all `import`s above non-import statements.
1350
- eslint: [`import/first`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/first.md)
1351
- > Why? Since `import`s are hoisted, keeping them all at the top prevents surprising behavior.
1352
-
1353
- ```javascript
1354
- // bad
1355
- import foo from 'foo';
1356
- foo.init();
1357
-
1358
- import bar from 'bar';
1359
-
1360
- // good
1361
- import foo from 'foo';
1362
- import bar from 'bar';
1363
-
1364
- foo.init();
1365
- ```
1366
-
1367
- <a name="modules--multiline-imports-over-newlines"></a>
1368
- - [10.8](#modules--multiline-imports-over-newlines) Multiline imports should be indented just like multiline array and object literals.
1369
-
1370
- > Why? The curly braces follow the same indentation rules as every other curly brace block in the style guide, as do the trailing commas.
1371
-
1372
- ```javascript
1373
- // bad
1374
- import {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path';
1375
-
1376
- // good
1377
- import {
1378
- longNameA,
1379
- longNameB,
1380
- longNameC,
1381
- longNameD,
1382
- longNameE,
1383
- } from 'path';
1384
- ```
1385
-
1386
- <a name="modules--no-webpack-loader-syntax"></a>
1387
- - [10.9](#modules--no-webpack-loader-syntax) Disallow Webpack loader syntax in module import statements.
1388
- eslint: [`import/no-webpack-loader-syntax`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-webpack-loader-syntax.md)
1389
- > Why? Since using Webpack syntax in the imports couples the code to a module bundler. Prefer using the loader syntax in `webpack.config.js`.
1390
-
1391
- ```javascript
1392
- // bad
1393
- import fooSass from 'css!sass!foo.scss';
1394
- import barCss from 'style!css!bar.css';
1395
-
1396
- // good
1397
- import fooSass from 'foo.scss';
1398
- import barCss from 'bar.css';
1399
- ```
1400
-
1401
- **[⬆ back to top](#table-of-contents)**
1402
-
1403
- ## Iterators and Generators
1404
-
1405
- <a name="iterators--nope"></a><a name="11.1"></a>
1406
- - [11.1](#iterators--nope) Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops like `for-in` or `for-of`. eslint: [`no-iterator`](https://eslint.org/docs/rules/no-iterator.html) [`no-restricted-syntax`](https://eslint.org/docs/rules/no-restricted-syntax)
1407
-
1408
- > Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
1409
-
1410
- > Use `map()` / `every()` / `filter()` / `find()` / `findIndex()` / `reduce()` / `some()` / ... to iterate over arrays, and `Object.keys()` / `Object.values()` / `Object.entries()` to produce arrays so you can iterate over objects.
1411
-
1412
- ```javascript
1413
- const numbers = [1, 2, 3, 4, 5];
1414
-
1415
- // bad
1416
- let sum = 0;
1417
- for (let num of numbers) {
1418
- sum += num;
1419
- }
1420
- sum === 15;
1421
-
1422
- // good
1423
- let sum = 0;
1424
- numbers.forEach((num) => {
1425
- sum += num;
1426
- });
1427
- sum === 15;
1428
-
1429
- // best (use the functional force)
1430
- const sum = numbers.reduce((total, num) => total + num, 0);
1431
- sum === 15;
1432
-
1433
- // bad
1434
- const increasedByOne = [];
1435
- for (let i = 0; i < numbers.length; i++) {
1436
- increasedByOne.push(numbers[i] + 1);
1437
- }
1438
-
1439
- // good
1440
- const increasedByOne = [];
1441
- numbers.forEach((num) => {
1442
- increasedByOne.push(num + 1);
1443
- });
1444
-
1445
- // best (keeping it functional)
1446
- const increasedByOne = numbers.map((num) => num + 1);
1447
- ```
1448
-
1449
- <a name="generators--nope"></a><a name="11.2"></a>
1450
- - [11.2](#generators--nope) Don’t use generators for now.
1451
-
1452
- > Why? They don’t transpile well to ES5.
1453
-
1454
- <a name="generators--spacing"></a>
1455
- - [11.3](#generators--spacing) If you must use generators, or if you disregard [our advice](#generators--nope), make sure their function signature is spaced properly. eslint: [`generator-star-spacing`](https://eslint.org/docs/rules/generator-star-spacing)
1456
-
1457
- > Why? `function` and `*` are part of the same conceptual keyword - `*` is not a modifier for `function`, `function*` is a unique construct, different from `function`.
1458
-
1459
- ```javascript
1460
- // bad
1461
- function * foo() {
1462
- // ...
1463
- }
1464
-
1465
- // bad
1466
- const bar = function * () {
1467
- // ...
1468
- };
1469
-
1470
- // bad
1471
- const baz = function *() {
1472
- // ...
1473
- };
1474
-
1475
- // bad
1476
- const quux = function*() {
1477
- // ...
1478
- };
1479
-
1480
- // bad
1481
- function*foo() {
1482
- // ...
1483
- }
1484
-
1485
- // bad
1486
- function *foo() {
1487
- // ...
1488
- }
1489
-
1490
- // very bad
1491
- function
1492
- *
1493
- foo() {
1494
- // ...
1495
- }
1496
-
1497
- // very bad
1498
- const wat = function
1499
- *
1500
- () {
1501
- // ...
1502
- };
1503
-
1504
- // good
1505
- function* foo() {
1506
- // ...
1507
- }
1508
-
1509
- // good
1510
- const foo = function* () {
1511
- // ...
1512
- };
1513
- ```
1514
-
1515
- **[⬆ back to top](#table-of-contents)**
1516
-
1517
- ## Properties
1518
-
1519
- <a name="properties--dot"></a><a name="12.1"></a>
1520
- - [12.1](#properties--dot) Use dot notation when accessing properties. eslint: [`dot-notation`](https://eslint.org/docs/rules/dot-notation.html)
1521
-
1522
- ```javascript
1523
- const luke = {
1524
- jedi: true,
1525
- age: 28,
1526
- };
1527
-
1528
- // bad
1529
- const isJedi = luke['jedi'];
1530
-
1531
- // good
1532
- const isJedi = luke.jedi;
1533
- ```
1534
-
1535
- <a name="properties--bracket"></a><a name="12.2"></a>
1536
- - [12.2](#properties--bracket) Use bracket notation `[]` when accessing properties with a variable.
1537
-
1538
- ```javascript
1539
- const luke = {
1540
- jedi: true,
1541
- age: 28,
1542
- };
1543
-
1544
- function getProp(prop) {
1545
- return luke[prop];
1546
- }
1547
-
1548
- const isJedi = getProp('jedi');
1549
- ```
1550
-
1551
- <a name="es2016-properties--exponentiation-operator"></a>
1552
- - [12.3](#es2016-properties--exponentiation-operator) Use exponentiation operator `**` when calculating exponentiations. eslint: [`no-restricted-properties`](https://eslint.org/docs/rules/no-restricted-properties).
1553
-
1554
- ```javascript
1555
- // bad
1556
- const binary = Math.pow(2, 10);
1557
-
1558
- // good
1559
- const binary = 2 ** 10;
1560
- ```
1561
-
1562
- **[⬆ back to top](#table-of-contents)**
1563
-
1564
- ## Variables
1565
-
1566
- <a name="variables--const"></a><a name="13.1"></a>
1567
- - [13.1](#variables--const) Always use `const` or `let` to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that. eslint: [`no-undef`](https://eslint.org/docs/rules/no-undef) [`prefer-const`](https://eslint.org/docs/rules/prefer-const)
1568
-
1569
- ```javascript
1570
- // bad
1571
- superPower = new SuperPower();
1572
-
1573
- // good
1574
- const superPower = new SuperPower();
1575
- ```
1576
-
1577
- <a name="variables--one-const"></a><a name="13.2"></a>
1578
- - [13.2](#variables--one-const) Use one `const` or `let` declaration per variable or assignment. eslint: [`one-var`](https://eslint.org/docs/rules/one-var.html)
1579
-
1580
- > Why? It’s easier to add new variable declarations this way, and you never have to worry about swapping out a `;` for a `,` or introducing punctuation-only diffs. You can also step through each declaration with the debugger, instead of jumping through all of them at once.
1581
-
1582
- ```javascript
1583
- // bad
1584
- const items = getItems(),
1585
- goSportsTeam = true,
1586
- dragonball = 'z';
1587
-
1588
- // bad
1589
- // (compare to above, and try to spot the mistake)
1590
- const items = getItems(),
1591
- goSportsTeam = true;
1592
- dragonball = 'z';
1593
-
1594
- // good
1595
- const items = getItems();
1596
- const goSportsTeam = true;
1597
- const dragonball = 'z';
1598
- ```
1599
-
1600
- <a name="variables--const-let-group"></a><a name="13.3"></a>
1601
- - [13.3](#variables--const-let-group) Group all your `const`s and then group all your `let`s.
1602
-
1603
- > Why? This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
1604
-
1605
- ```javascript
1606
- // bad
1607
- let i, len, dragonball,
1608
- items = getItems(),
1609
- goSportsTeam = true;
1610
-
1611
- // bad
1612
- let i;
1613
- const items = getItems();
1614
- let dragonball;
1615
- const goSportsTeam = true;
1616
- let len;
1617
-
1618
- // good
1619
- const goSportsTeam = true;
1620
- const items = getItems();
1621
- let dragonball;
1622
- let i;
1623
- let length;
1624
- ```
1625
-
1626
- <a name="variables--define-where-used"></a><a name="13.4"></a>
1627
- - [13.4](#variables--define-where-used) Assign variables where you need them, but place them in a reasonable place.
1628
-
1629
- > Why? `let` and `const` are block scoped and not function scoped.
1630
-
1631
- ```javascript
1632
- // bad - unnecessary function call
1633
- function checkName(hasName) {
1634
- const name = getName();
1635
-
1636
- if (hasName === 'test') {
1637
- return false;
1638
- }
1639
-
1640
- if (name === 'test') {
1641
- this.setName('');
1642
- return false;
1643
- }
1644
-
1645
- return name;
1646
- }
1647
-
1648
- // good
1649
- function checkName(hasName) {
1650
- if (hasName === 'test') {
1651
- return false;
1652
- }
1653
-
1654
- const name = getName();
1655
-
1656
- if (name === 'test') {
1657
- this.setName('');
1658
- return false;
1659
- }
1660
-
1661
- return name;
1662
- }
1663
- ```
1664
-
1665
- <a name="variables--no-chain-assignment"></a><a name="13.5"></a>
1666
- - [13.5](#variables--no-chain-assignment) Don’t chain variable assignments. eslint: [`no-multi-assign`](https://eslint.org/docs/rules/no-multi-assign)
1667
-
1668
- > Why? Chaining variable assignments creates implicit global variables.
1669
-
1670
- ```javascript
1671
- // bad
1672
- (function example() {
1673
- // JavaScript interprets this as
1674
- // let a = ( b = ( c = 1 ) );
1675
- // The let keyword only applies to variable a; variables b and c become
1676
- // global variables.
1677
- let a = b = c = 1;
1678
- }());
1679
-
1680
- console.log(a); // throws ReferenceError
1681
- console.log(b); // 1
1682
- console.log(c); // 1
1683
-
1684
- // good
1685
- (function example() {
1686
- let a = 1;
1687
- let b = a;
1688
- let c = a;
1689
- }());
1690
-
1691
- console.log(a); // throws ReferenceError
1692
- console.log(b); // throws ReferenceError
1693
- console.log(c); // throws ReferenceError
1694
-
1695
- // the same applies for `const`
1696
- ```
1697
-
1698
- <a name="variables--unary-increment-decrement"></a><a name="13.6"></a>
1699
- - [13.6](#variables--unary-increment-decrement) Avoid using unary increments and decrements (`++`, `--`). eslint [`no-plusplus`](https://eslint.org/docs/rules/no-plusplus)
1700
-
1701
- > Why? Per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application. It is also more expressive to mutate your values with statements like `num += 1` instead of `num++` or `num ++`. Disallowing unary increment and decrement statements also prevents you from pre-incrementing/pre-decrementing values unintentionally which can also cause unexpected behavior in your programs.
1702
-
1703
- ```javascript
1704
- // bad
1705
-
1706
- const array = [1, 2, 3];
1707
- let num = 1;
1708
- num++;
1709
- --num;
1710
-
1711
- let sum = 0;
1712
- let truthyCount = 0;
1713
- for (let i = 0; i < array.length; i++) {
1714
- let value = array[i];
1715
- sum += value;
1716
- if (value) {
1717
- truthyCount++;
1718
- }
1719
- }
1720
-
1721
- // good
1722
-
1723
- const array = [1, 2, 3];
1724
- let num = 1;
1725
- num += 1;
1726
- num -= 1;
1727
-
1728
- const sum = array.reduce((a, b) => a + b, 0);
1729
- const truthyCount = array.filter(Boolean).length;
1730
- ```
1731
-
1732
- <a name="variables--linebreak"></a>
1733
- - [13.7](#variables--linebreak) Avoid linebreaks before or after `=` in an assignment. If your assignment violates [`max-len`](https://eslint.org/docs/rules/max-len.html), surround the value in parens. eslint [`operator-linebreak`](https://eslint.org/docs/rules/operator-linebreak.html).
1734
-
1735
- > Why? Linebreaks surrounding `=` can obfuscate the value of an assignment.
1736
-
1737
- ```javascript
1738
- // bad
1739
- const foo =
1740
- superLongLongLongLongLongLongLongLongFunctionName();
1741
-
1742
- // bad
1743
- const foo
1744
- = 'superLongLongLongLongLongLongLongLongString';
1745
-
1746
- // good
1747
- const foo = (
1748
- superLongLongLongLongLongLongLongLongFunctionName()
1749
- );
1750
-
1751
- // good
1752
- const foo = 'superLongLongLongLongLongLongLongLongString';
1753
- ```
1754
-
1755
- <a name="variables--no-unused-vars"></a>
1756
- - [13.8](#variables--no-unused-vars) Disallow unused variables. eslint: [`no-unused-vars`](https://eslint.org/docs/rules/no-unused-vars)
1757
-
1758
- > Why? Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.
1759
-
1760
- ```javascript
1761
- // bad
1762
-
1763
- var some_unused_var = 42;
1764
-
1765
- // Write-only variables are not considered as used.
1766
- var y = 10;
1767
- y = 5;
1768
-
1769
- // A read for a modification of itself is not considered as used.
1770
- var z = 0;
1771
- z = z + 1;
1772
-
1773
- // Unused function arguments.
1774
- function getX(x, y) {
1775
- return x;
1776
- }
1777
-
1778
- // good
1779
-
1780
- function getXPlusY(x, y) {
1781
- return x + y;
1782
- }
1783
-
1784
- var x = 1;
1785
- var y = a + 2;
1786
-
1787
- alert(getXPlusY(x, y));
1788
-
1789
- // 'type' is ignored even if unused because it has a rest property sibling.
1790
- // This is a form of extracting an object that omits the specified keys.
1791
- var { type, ...coords } = data;
1792
- // 'coords' is now the 'data' object without its 'type' property.
1793
- ```
1794
-
1795
- **[⬆ back to top](#table-of-contents)**
1796
-
1797
- ## Hoisting
1798
-
1799
- <a name="hoisting--about"></a><a name="14.1"></a>
1800
- - [14.1](#hoisting--about) `var` declarations get hoisted to the top of their closest enclosing function 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). It’s important to know why [typeof is no longer safe](http://es-discourse.com/t/why-typeof-is-no-longer-safe/15).
1801
-
1802
- ```javascript
1803
- // we know this wouldn’t work (assuming there
1804
- // is no notDefined global variable)
1805
- function example() {
1806
- console.log(notDefined); // => throws a ReferenceError
1807
- }
1808
-
1809
- // creating a variable declaration after you
1810
- // reference the variable will work due to
1811
- // variable hoisting. Note: the assignment
1812
- // value of `true` is not hoisted.
1813
- function example() {
1814
- console.log(declaredButNotAssigned); // => undefined
1815
- var declaredButNotAssigned = true;
1816
- }
1817
-
1818
- // the interpreter is hoisting the variable
1819
- // declaration to the top of the scope,
1820
- // which means our example could be rewritten as:
1821
- function example() {
1822
- let declaredButNotAssigned;
1823
- console.log(declaredButNotAssigned); // => undefined
1824
- declaredButNotAssigned = true;
1825
- }
1826
-
1827
- // using const and let
1828
- function example() {
1829
- console.log(declaredButNotAssigned); // => throws a ReferenceError
1830
- console.log(typeof declaredButNotAssigned); // => throws a ReferenceError
1831
- const declaredButNotAssigned = true;
1832
- }
1833
- ```
1834
-
1835
- <a name="hoisting--anon-expressions"></a><a name="14.2"></a>
1836
- - [14.2](#hoisting--anon-expressions) Anonymous function expressions hoist their variable name, but not the function assignment.
1837
-
1838
- ```javascript
1839
- function example() {
1840
- console.log(anonymous); // => undefined
1841
-
1842
- anonymous(); // => TypeError anonymous is not a function
1843
-
1844
- var anonymous = function () {
1845
- console.log('anonymous function expression');
1846
- };
1847
- }
1848
- ```
1849
-
1850
- <a name="hoisting--named-expresions"></a><a name="hoisting--named-expressions"></a><a name="14.3"></a>
1851
- - [14.3](#hoisting--named-expressions) Named function expressions hoist the variable name, not the function name or the function body.
1852
-
1853
- ```javascript
1854
- function example() {
1855
- console.log(named); // => undefined
1856
-
1857
- named(); // => TypeError named is not a function
1858
-
1859
- superPower(); // => ReferenceError superPower is not defined
1860
-
1861
- var named = function superPower() {
1862
- console.log('Flying');
1863
- };
1864
- }
1865
-
1866
- // the same is true when the function name
1867
- // is the same as the variable name.
1868
- function example() {
1869
- console.log(named); // => undefined
1870
-
1871
- named(); // => TypeError named is not a function
1872
-
1873
- var named = function named() {
1874
- console.log('named');
1875
- };
1876
- }
1877
- ```
1878
-
1879
- <a name="hoisting--declarations"></a><a name="14.4"></a>
1880
- - [14.4](#hoisting--declarations) Function declarations hoist their name and the function body.
1881
-
1882
- ```javascript
1883
- function example() {
1884
- superPower(); // => Flying
1885
-
1886
- function superPower() {
1887
- console.log('Flying');
1888
- }
1889
- }
1890
- ```
1891
-
1892
- - 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/).
1893
-
1894
- **[⬆ back to top](#table-of-contents)**
1895
-
1896
- ## Comparison Operators & Equality
1897
-
1898
- <a name="comparison--eqeqeq"></a><a name="15.1"></a>
1899
- - [15.1](#comparison--eqeqeq) Use `===` and `!==` over `==` and `!=`. eslint: [`eqeqeq`](https://eslint.org/docs/rules/eqeqeq.html)
1900
-
1901
- <a name="comparison--if"></a><a name="15.2"></a>
1902
- - [15.2](#comparison--if) Conditional statements such as the `if` statement evaluate their expression using coercion with the `ToBoolean` abstract method and always follow these simple rules:
1903
-
1904
- - **Objects** evaluate to **true**
1905
- - **Undefined** evaluates to **false**
1906
- - **Null** evaluates to **false**
1907
- - **Booleans** evaluate to **the value of the boolean**
1908
- - **Numbers** evaluate to **false** if **+0, -0, or NaN**, otherwise **true**
1909
- - **Strings** evaluate to **false** if an empty string `''`, otherwise **true**
1910
-
1911
- ```javascript
1912
- if ([0] && []) {
1913
- // true
1914
- // an array (even an empty one) is an object, objects will evaluate to true
1915
- }
1916
- ```
1917
-
1918
- <a name="comparison--shortcuts"></a><a name="15.3"></a>
1919
- - [15.3](#comparison--shortcuts) Use shortcuts for booleans, but explicit comparisons for strings and numbers.
1920
-
1921
- ```javascript
1922
- // bad
1923
- if (isValid === true) {
1924
- // ...
1925
- }
1926
-
1927
- // good
1928
- if (isValid) {
1929
- // ...
1930
- }
1931
-
1932
- // bad
1933
- if (name) {
1934
- // ...
1935
- }
1936
-
1937
- // good
1938
- if (name !== '') {
1939
- // ...
1940
- }
1941
-
1942
- // bad
1943
- if (collection.length) {
1944
- // ...
1945
- }
1946
-
1947
- // good
1948
- if (collection.length > 0) {
1949
- // ...
1950
- }
1951
- ```
1952
-
1953
- <a name="comparison--moreinfo"></a><a name="15.4"></a>
1954
- - [15.4](#comparison--moreinfo) For more information see [Truth Equality and JavaScript](https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) by Angus Croll.
1955
-
1956
- <a name="comparison--switch-blocks"></a><a name="15.5"></a>
1957
- - [15.5](#comparison--switch-blocks) Use braces to create blocks in `case` and `default` clauses that contain lexical declarations (e.g. `let`, `const`, `function`, and `class`). eslint: [`no-case-declarations`](https://eslint.org/docs/rules/no-case-declarations.html)
1958
-
1959
- > Why? Lexical declarations are visible in the entire `switch` block but only get initialized when assigned, which only happens when its `case` is reached. This causes problems when multiple `case` clauses attempt to define the same thing.
1960
-
1961
- ```javascript
1962
- // bad
1963
- switch (foo) {
1964
- case 1:
1965
- let x = 1;
1966
- break;
1967
- case 2:
1968
- const y = 2;
1969
- break;
1970
- case 3:
1971
- function f() {
1972
- // ...
1973
- }
1974
- break;
1975
- default:
1976
- class C {}
1977
- }
1978
-
1979
- // good
1980
- switch (foo) {
1981
- case 1: {
1982
- let x = 1;
1983
- break;
1984
- }
1985
- case 2: {
1986
- const y = 2;
1987
- break;
1988
- }
1989
- case 3: {
1990
- function f() {
1991
- // ...
1992
- }
1993
- break;
1994
- }
1995
- case 4:
1996
- bar();
1997
- break;
1998
- default: {
1999
- class C {}
2000
- }
2001
- }
2002
- ```
2003
-
2004
- <a name="comparison--nested-ternaries"></a><a name="15.6"></a>
2005
- - [15.6](#comparison--nested-ternaries) Ternaries should not be nested and generally be single line expressions. eslint: [`no-nested-ternary`](https://eslint.org/docs/rules/no-nested-ternary.html)
2006
-
2007
- ```javascript
2008
- // bad
2009
- const foo = maybe1 > maybe2
2010
- ? "bar"
2011
- : value1 > value2 ? "baz" : null;
2012
-
2013
- // split into 2 separated ternary expressions
2014
- const maybeNull = value1 > value2 ? 'baz' : null;
2015
-
2016
- // better
2017
- const foo = maybe1 > maybe2
2018
- ? 'bar'
2019
- : maybeNull;
2020
-
2021
- // best
2022
- const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
2023
- ```
2024
-
2025
- <a name="comparison--unneeded-ternary"></a><a name="15.7"></a>
2026
- - [15.7](#comparison--unneeded-ternary) Avoid unneeded ternary statements. eslint: [`no-unneeded-ternary`](https://eslint.org/docs/rules/no-unneeded-ternary.html)
2027
-
2028
- ```javascript
2029
- // bad
2030
- const foo = a ? a : b;
2031
- const bar = c ? true : false;
2032
- const baz = c ? false : true;
2033
-
2034
- // good
2035
- const foo = a || b;
2036
- const bar = !!c;
2037
- const baz = !c;
2038
- ```
2039
-
2040
- <a name="comparison--no-mixed-operators"></a>
2041
- - [15.8](#comparison--no-mixed-operators) When mixing operators, enclose them in parentheses. The only exception is the standard arithmetic operators: `+`, `-`, and `**` since their precedence is broadly understood. We recommend enclosing `/` and `*` in parentheses because their precedence can be ambiguous when they are mixed.
2042
- eslint: [`no-mixed-operators`](https://eslint.org/docs/rules/no-mixed-operators.html)
2043
-
2044
- > Why? This improves readability and clarifies the developer’s intention.
2045
-
2046
- ```javascript
2047
- // bad
2048
- const foo = a && b < 0 || c > 0 || d + 1 === 0;
2049
-
2050
- // bad
2051
- const bar = a ** b - 5 % d;
2052
-
2053
- // bad
2054
- // one may be confused into thinking (a || b) && c
2055
- if (a || b && c) {
2056
- return d;
2057
- }
2058
-
2059
- // bad
2060
- const bar = a + b / c * d;
2061
-
2062
- // good
2063
- const foo = (a && b < 0) || c > 0 || (d + 1 === 0);
2064
-
2065
- // good
2066
- const bar = a ** b - (5 % d);
2067
-
2068
- // good
2069
- if (a || (b && c)) {
2070
- return d;
2071
- }
2072
-
2073
- // good
2074
- const bar = a + (b / c) * d;
2075
- ```
2076
-
2077
- **[⬆ back to top](#table-of-contents)**
2078
-
2079
- ## Blocks
2080
-
2081
- <a name="blocks--braces"></a><a name="16.1"></a>
2082
- - [16.1](#blocks--braces) Use braces with all multi-line blocks. eslint: [`nonblock-statement-body-position`](https://eslint.org/docs/rules/nonblock-statement-body-position)
2083
-
2084
- ```javascript
2085
- // bad
2086
- if (test)
2087
- return false;
2088
-
2089
- // good
2090
- if (test) return false;
2091
-
2092
- // good
2093
- if (test) {
2094
- return false;
2095
- }
2096
-
2097
- // bad
2098
- function foo() { return false; }
2099
-
2100
- // good
2101
- function bar() {
2102
- return false;
2103
- }
2104
- ```
2105
-
2106
- <a name="blocks--cuddled-elses"></a><a name="16.2"></a>
2107
- - [16.2](#blocks--cuddled-elses) If you’re using multi-line blocks with `if` and `else`, put `else` on the same line as your `if` block’s closing brace. eslint: [`brace-style`](https://eslint.org/docs/rules/brace-style.html)
2108
-
2109
- ```javascript
2110
- // bad
2111
- if (test) {
2112
- thing1();
2113
- thing2();
2114
- }
2115
- else {
2116
- thing3();
2117
- }
2118
-
2119
- // good
2120
- if (test) {
2121
- thing1();
2122
- thing2();
2123
- } else {
2124
- thing3();
2125
- }
2126
- ```
2127
-
2128
- <a name="blocks--no-else-return"></a><a name="16.3"></a>
2129
- - [16.3](#blocks--no-else-return) If an `if` block always executes a `return` statement, the subsequent `else` block is unnecessary. A `return` in an `else if` block following an `if` block that contains a `return` can be separated into multiple `if` blocks. eslint: [`no-else-return`](https://eslint.org/docs/rules/no-else-return)
2130
-
2131
- ```javascript
2132
- // bad
2133
- function foo() {
2134
- if (x) {
2135
- return x;
2136
- } else {
2137
- return y;
2138
- }
2139
- }
2140
-
2141
- // bad
2142
- function cats() {
2143
- if (x) {
2144
- return x;
2145
- } else if (y) {
2146
- return y;
2147
- }
2148
- }
2149
-
2150
- // bad
2151
- function dogs() {
2152
- if (x) {
2153
- return x;
2154
- } else {
2155
- if (y) {
2156
- return y;
2157
- }
2158
- }
2159
- }
2160
-
2161
- // good
2162
- function foo() {
2163
- if (x) {
2164
- return x;
2165
- }
2166
-
2167
- return y;
2168
- }
2169
-
2170
- // good
2171
- function cats() {
2172
- if (x) {
2173
- return x;
2174
- }
2175
-
2176
- if (y) {
2177
- return y;
2178
- }
2179
- }
2180
-
2181
- // good
2182
- function dogs(x) {
2183
- if (x) {
2184
- if (z) {
2185
- return y;
2186
- }
2187
- } else {
2188
- return z;
2189
- }
2190
- }
2191
- ```
2192
-
2193
- **[⬆ back to top](#table-of-contents)**
2194
-
2195
- ## Control Statements
2196
-
2197
- <a name="control-statements"></a>
2198
- - [17.1](#control-statements) In case your control statement (`if`, `while` etc.) gets too long or exceeds the maximum line length, each (grouped) condition could be put into a new line. The logical operator should begin the line.
2199
-
2200
- > Why? Requiring operators at the beginning of the line keeps the operators aligned and follows a pattern similar to method chaining. This also improves readability by making it easier to visually follow complex logic.
2201
-
2202
- ```javascript
2203
- // bad
2204
- if ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) {
2205
- thing1();
2206
- }
2207
-
2208
- // bad
2209
- if (foo === 123 &&
2210
- bar === 'abc') {
2211
- thing1();
2212
- }
2213
-
2214
- // bad
2215
- if (foo === 123
2216
- && bar === 'abc') {
2217
- thing1();
2218
- }
2219
-
2220
- // bad
2221
- if (
2222
- foo === 123 &&
2223
- bar === 'abc'
2224
- ) {
2225
- thing1();
2226
- }
2227
-
2228
- // good
2229
- if (
2230
- foo === 123
2231
- && bar === 'abc'
2232
- ) {
2233
- thing1();
2234
- }
2235
-
2236
- // good
2237
- if (
2238
- (foo === 123 || bar === 'abc')
2239
- && doesItLookGoodWhenItBecomesThatLong()
2240
- && isThisReallyHappening()
2241
- ) {
2242
- thing1();
2243
- }
2244
-
2245
- // good
2246
- if (foo === 123 && bar === 'abc') {
2247
- thing1();
2248
- }
2249
- ```
2250
-
2251
- <a name="control-statement--value-selection"></a><a name="control-statements--value-selection"></a>
2252
- - [17.2](#control-statements--value-selection) Don't use selection operators in place of control statements.
2253
-
2254
- ```javascript
2255
- // bad
2256
- !isRunning && startRunning();
2257
-
2258
- // good
2259
- if (!isRunning) {
2260
- startRunning();
2261
- }
2262
- ```
2263
-
2264
- **[⬆ back to top](#table-of-contents)**
2265
-
2266
- ## Comments
2267
-
2268
- <a name="comments--multiline"></a><a name="17.1"></a>
2269
- - [18.1](#comments--multiline) Use `/** ... */` for multi-line comments.
2270
-
2271
- ```javascript
2272
- // bad
2273
- // make() returns a new element
2274
- // based on the passed in tag name
2275
- //
2276
- // @param {String} tag
2277
- // @return {Element} element
2278
- function make(tag) {
2279
-
2280
- // ...
2281
-
2282
- return element;
2283
- }
2284
-
2285
- // good
2286
- /**
2287
- * make() returns a new element
2288
- * based on the passed-in tag name
2289
- */
2290
- function make(tag) {
2291
-
2292
- // ...
2293
-
2294
- return element;
2295
- }
2296
- ```
2297
-
2298
- <a name="comments--singleline"></a><a name="17.2"></a>
2299
- - [18.2](#comments--singleline) Use `//` for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it’s on the first line of a block.
2300
-
2301
- ```javascript
2302
- // bad
2303
- const active = true; // is current tab
2304
-
2305
- // good
2306
- // is current tab
2307
- const active = true;
2308
-
2309
- // bad
2310
- function getType() {
2311
- console.log('fetching type...');
2312
- // set the default type to 'no type'
2313
- const type = this.type || 'no type';
2314
-
2315
- return type;
2316
- }
2317
-
2318
- // good
2319
- function getType() {
2320
- console.log('fetching type...');
2321
-
2322
- // set the default type to 'no type'
2323
- const type = this.type || 'no type';
2324
-
2325
- return type;
2326
- }
2327
-
2328
- // also good
2329
- function getType() {
2330
- // set the default type to 'no type'
2331
- const type = this.type || 'no type';
2332
-
2333
- return type;
2334
- }
2335
- ```
2336
-
2337
- <a name="comments--spaces"></a>
2338
- - [18.3](#comments--spaces) Start all comments with a space to make it easier to read. eslint: [`spaced-comment`](https://eslint.org/docs/rules/spaced-comment)
2339
-
2340
- ```javascript
2341
- // bad
2342
- //is current tab
2343
- const active = true;
2344
-
2345
- // good
2346
- // is current tab
2347
- const active = true;
2348
-
2349
- // bad
2350
- /**
2351
- *make() returns a new element
2352
- *based on the passed-in tag name
2353
- */
2354
- function make(tag) {
2355
-
2356
- // ...
2357
-
2358
- return element;
2359
- }
2360
-
2361
- // good
2362
- /**
2363
- * make() returns a new element
2364
- * based on the passed-in tag name
2365
- */
2366
- function make(tag) {
2367
-
2368
- // ...
2369
-
2370
- return element;
2371
- }
2372
- ```
2373
-
2374
- <a name="comments--actionitems"></a><a name="17.3"></a>
2375
- - [18.4](#comments--actionitems) Prefixing your comments with `FIXME` or `TODO` helps other developers quickly understand if you’re pointing out a problem that needs to be revisited, or if you’re suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are `FIXME: -- need to figure this out` or `TODO: -- need to implement`.
2376
-
2377
- <a name="comments--fixme"></a><a name="17.4"></a>
2378
- - [18.5](#comments--fixme) Use `// FIXME:` to annotate problems.
2379
-
2380
- ```javascript
2381
- class Calculator extends Abacus {
2382
- constructor() {
2383
- super();
2384
-
2385
- // FIXME: shouldn’t use a global here
2386
- total = 0;
2387
- }
2388
- }
2389
- ```
2390
-
2391
- <a name="comments--todo"></a><a name="17.5"></a>
2392
- - [18.6](#comments--todo) Use `// TODO:` to annotate solutions to problems.
2393
-
2394
- ```javascript
2395
- class Calculator extends Abacus {
2396
- constructor() {
2397
- super();
2398
-
2399
- // TODO: total should be configurable by an options param
2400
- this.total = 0;
2401
- }
2402
- }
2403
- ```
2404
-
2405
- **[⬆ back to top](#table-of-contents)**
2406
-
2407
- ## Whitespace
2408
-
2409
- <a name="whitespace--spaces"></a><a name="18.1"></a>
2410
- - [19.1](#whitespace--spaces) Use soft tabs (space character) set to 2 spaces. eslint: [`indent`](https://eslint.org/docs/rules/indent.html)
2411
-
2412
- ```javascript
2413
- // bad
2414
- function foo() {
2415
- ∙∙∙∙let name;
2416
- }
2417
-
2418
- // bad
2419
- function bar() {
2420
- ∙let name;
2421
- }
2422
-
2423
- // good
2424
- function baz() {
2425
- ∙∙let name;
2426
- }
2427
- ```
2428
-
2429
- <a name="whitespace--before-blocks"></a><a name="18.2"></a>
2430
- - [19.2](#whitespace--before-blocks) Place 1 space before the leading brace. eslint: [`space-before-blocks`](https://eslint.org/docs/rules/space-before-blocks.html)
2431
-
2432
- ```javascript
2433
- // bad
2434
- function test(){
2435
- console.log('test');
2436
- }
2437
-
2438
- // good
2439
- function test() {
2440
- console.log('test');
2441
- }
2442
-
2443
- // bad
2444
- dog.set('attr',{
2445
- age: '1 year',
2446
- breed: 'Bernese Mountain Dog',
2447
- });
2448
-
2449
- // good
2450
- dog.set('attr', {
2451
- age: '1 year',
2452
- breed: 'Bernese Mountain Dog',
2453
- });
2454
- ```
2455
-
2456
- <a name="whitespace--around-keywords"></a><a name="18.3"></a>
2457
- - [19.3](#whitespace--around-keywords) Place 1 space before the opening parenthesis in control statements (`if`, `while` etc.). Place no space between the argument list and the function name in function calls and declarations. eslint: [`keyword-spacing`](https://eslint.org/docs/rules/keyword-spacing.html)
2458
-
2459
- ```javascript
2460
- // bad
2461
- if(isJedi) {
2462
- fight ();
2463
- }
2464
-
2465
- // good
2466
- if (isJedi) {
2467
- fight();
2468
- }
2469
-
2470
- // bad
2471
- function fight () {
2472
- console.log ('Swooosh!');
2473
- }
2474
-
2475
- // good
2476
- function fight() {
2477
- console.log('Swooosh!');
2478
- }
2479
- ```
2480
-
2481
- <a name="whitespace--infix-ops"></a><a name="18.4"></a>
2482
- - [19.4](#whitespace--infix-ops) Set off operators with spaces. eslint: [`space-infix-ops`](https://eslint.org/docs/rules/space-infix-ops.html)
2483
-
2484
- ```javascript
2485
- // bad
2486
- const x=y+5;
2487
-
2488
- // good
2489
- const x = y + 5;
2490
- ```
2491
-
2492
- <a name="whitespace--newline-at-end"></a><a name="18.5"></a>
2493
- - [19.5](#whitespace--newline-at-end) End files with a single newline character. eslint: [`eol-last`](https://github.com/eslint/eslint/blob/master/docs/rules/eol-last.md)
2494
-
2495
- ```javascript
2496
- // bad
2497
- import { es6 } from './AirbnbStyleGuide';
2498
- // ...
2499
- export default es6;
2500
- ```
2501
-
2502
- ```javascript
2503
- // bad
2504
- import { es6 } from './AirbnbStyleGuide';
2505
- // ...
2506
- export default es6;↵
2507
-
2508
- ```
2509
-
2510
- ```javascript
2511
- // good
2512
- import { es6 } from './AirbnbStyleGuide';
2513
- // ...
2514
- export default es6;↵
2515
- ```
2516
-
2517
- <a name="whitespace--chains"></a><a name="18.6"></a>
2518
- - [19.6](#whitespace--chains) Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which
2519
- emphasizes that the line is a method call, not a new statement. eslint: [`newline-per-chained-call`](https://eslint.org/docs/rules/newline-per-chained-call) [`no-whitespace-before-property`](https://eslint.org/docs/rules/no-whitespace-before-property)
2520
-
2521
- ```javascript
2522
- // bad
2523
- $('#items').find('.selected').highlight().end().find('.open').updateCount();
2524
-
2525
- // bad
2526
- $('#items').
2527
- find('.selected').
2528
- highlight().
2529
- end().
2530
- find('.open').
2531
- updateCount();
2532
-
2533
- // good
2534
- $('#items')
2535
- .find('.selected')
2536
- .highlight()
2537
- .end()
2538
- .find('.open')
2539
- .updateCount();
2540
-
2541
- // bad
2542
- const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true)
2543
- .attr('width', (radius + margin) * 2).append('svg:g')
2544
- .attr('transform', `translate(${radius + margin},${radius + margin})`)
2545
- .call(tron.led);
2546
-
2547
- // good
2548
- const leds = stage.selectAll('.led')
2549
- .data(data)
2550
- .enter().append('svg:svg')
2551
- .classed('led', true)
2552
- .attr('width', (radius + margin) * 2)
2553
- .append('svg:g')
2554
- .attr('transform', `translate(${radius + margin},${radius + margin})`)
2555
- .call(tron.led);
2556
-
2557
- // good
2558
- const leds = stage.selectAll('.led').data(data);
2559
- ```
2560
-
2561
- <a name="whitespace--after-blocks"></a><a name="18.7"></a>
2562
- - [19.7](#whitespace--after-blocks) Leave a blank line after blocks and before the next statement.
2563
-
2564
- ```javascript
2565
- // bad
2566
- if (foo) {
2567
- return bar;
2568
- }
2569
- return baz;
2570
-
2571
- // good
2572
- if (foo) {
2573
- return bar;
2574
- }
2575
-
2576
- return baz;
2577
-
2578
- // bad
2579
- const obj = {
2580
- foo() {
2581
- },
2582
- bar() {
2583
- },
2584
- };
2585
- return obj;
2586
-
2587
- // good
2588
- const obj = {
2589
- foo() {
2590
- },
2591
-
2592
- bar() {
2593
- },
2594
- };
2595
-
2596
- return obj;
2597
-
2598
- // bad
2599
- const arr = [
2600
- function foo() {
2601
- },
2602
- function bar() {
2603
- },
2604
- ];
2605
- return arr;
2606
-
2607
- // good
2608
- const arr = [
2609
- function foo() {
2610
- },
2611
-
2612
- function bar() {
2613
- },
2614
- ];
2615
-
2616
- return arr;
2617
- ```
2618
-
2619
- <a name="whitespace--padded-blocks"></a><a name="18.8"></a>
2620
- - [19.8](#whitespace--padded-blocks) Do not pad your blocks with blank lines. eslint: [`padded-blocks`](https://eslint.org/docs/rules/padded-blocks.html)
2621
-
2622
- ```javascript
2623
- // bad
2624
- function bar() {
2625
-
2626
- console.log(foo);
2627
-
2628
- }
2629
-
2630
- // bad
2631
- if (baz) {
2632
-
2633
- console.log(qux);
2634
- } else {
2635
- console.log(foo);
2636
-
2637
- }
2638
-
2639
- // bad
2640
- class Foo {
2641
-
2642
- constructor(bar) {
2643
- this.bar = bar;
2644
- }
2645
- }
2646
-
2647
- // good
2648
- function bar() {
2649
- console.log(foo);
2650
- }
2651
-
2652
- // good
2653
- if (baz) {
2654
- console.log(qux);
2655
- } else {
2656
- console.log(foo);
2657
- }
2658
- ```
2659
-
2660
- <a name="whitespace--no-multiple-blanks"></a>
2661
- - [19.9](#whitespace--no-multiple-blanks) Do not use multiple blank lines to pad your code. eslint: [`no-multiple-empty-lines`](https://eslint.org/docs/rules/no-multiple-empty-lines)
2662
-
2663
- <!-- markdownlint-disable MD012 -->
2664
- ```javascript
2665
- // bad
2666
- class Person {
2667
- constructor(fullName, email, birthday) {
2668
- this.fullName = fullName;
2669
-
2670
-
2671
- this.email = email;
2672
-
2673
-
2674
- this.setAge(birthday);
2675
- }
2676
-
2677
-
2678
- setAge(birthday) {
2679
- const today = new Date();
2680
-
2681
-
2682
- const age = this.getAge(today, birthday);
2683
-
2684
-
2685
- this.age = age;
2686
- }
2687
-
2688
-
2689
- getAge(today, birthday) {
2690
- // ..
2691
- }
2692
- }
2693
-
2694
- // good
2695
- class Person {
2696
- constructor(fullName, email, birthday) {
2697
- this.fullName = fullName;
2698
- this.email = email;
2699
- this.setAge(birthday);
2700
- }
2701
-
2702
- setAge(birthday) {
2703
- const today = new Date();
2704
- const age = getAge(today, birthday);
2705
- this.age = age;
2706
- }
2707
-
2708
- getAge(today, birthday) {
2709
- // ..
2710
- }
2711
- }
2712
- ```
2713
-
2714
- <a name="whitespace--in-parens"></a><a name="18.9"></a>
2715
- - [19.10](#whitespace--in-parens) Do not add spaces inside parentheses. eslint: [`space-in-parens`](https://eslint.org/docs/rules/space-in-parens.html)
2716
-
2717
- ```javascript
2718
- // bad
2719
- function bar( foo ) {
2720
- return foo;
2721
- }
2722
-
2723
- // good
2724
- function bar(foo) {
2725
- return foo;
2726
- }
2727
-
2728
- // bad
2729
- if ( foo ) {
2730
- console.log(foo);
2731
- }
2732
-
2733
- // good
2734
- if (foo) {
2735
- console.log(foo);
2736
- }
2737
- ```
2738
-
2739
- <a name="whitespace--in-brackets"></a><a name="18.10"></a>
2740
- - [19.11](#whitespace--in-brackets) Do not add spaces inside brackets. eslint: [`array-bracket-spacing`](https://eslint.org/docs/rules/array-bracket-spacing.html)
2741
-
2742
- ```javascript
2743
- // bad
2744
- const foo = [ 1, 2, 3 ];
2745
- console.log(foo[ 0 ]);
2746
-
2747
- // good
2748
- const foo = [1, 2, 3];
2749
- console.log(foo[0]);
2750
- ```
2751
-
2752
- <a name="whitespace--in-braces"></a><a name="18.11"></a>
2753
- - [19.12](#whitespace--in-braces) Add spaces inside curly braces. eslint: [`object-curly-spacing`](https://eslint.org/docs/rules/object-curly-spacing.html)
2754
-
2755
- ```javascript
2756
- // bad
2757
- const foo = {clark: 'kent'};
2758
-
2759
- // good
2760
- const foo = { clark: 'kent' };
2761
- ```
2762
-
2763
- <a name="whitespace--max-len"></a><a name="18.12"></a>
2764
- - [19.13](#whitespace--max-len) Avoid having lines of code that are longer than 100 characters (including whitespace). Note: per [above](#strings--line-length), long strings are exempt from this rule, and should not be broken up. eslint: [`max-len`](https://eslint.org/docs/rules/max-len.html)
2765
-
2766
- > Why? This ensures readability and maintainability.
2767
-
2768
- ```javascript
2769
- // bad
2770
- const foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy;
2771
-
2772
- // bad
2773
- $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.'));
2774
-
2775
- // good
2776
- const foo = jsonData
2777
- && jsonData.foo
2778
- && jsonData.foo.bar
2779
- && jsonData.foo.bar.baz
2780
- && jsonData.foo.bar.baz.quux
2781
- && jsonData.foo.bar.baz.quux.xyzzy;
2782
-
2783
- // good
2784
- $.ajax({
2785
- method: 'POST',
2786
- url: 'https://airbnb.com/',
2787
- data: { name: 'John' },
2788
- })
2789
- .done(() => console.log('Congratulations!'))
2790
- .fail(() => console.log('You have failed this city.'));
2791
- ```
2792
-
2793
- <a name="whitespace--block-spacing"></a>
2794
- - [19.14](#whitespace--block-spacing) Require consistent spacing inside an open block token and the next token on the same line. This rule also enforces consistent spacing inside a close block token and previous token on the same line. eslint: [`block-spacing`](https://eslint.org/docs/rules/block-spacing)
2795
-
2796
- ```javascript
2797
- // bad
2798
- function foo() {return true;}
2799
- if (foo) { bar = 0;}
2800
-
2801
- // good
2802
- function foo() { return true; }
2803
- if (foo) { bar = 0; }
2804
- ```
2805
-
2806
- <a name="whitespace--comma-spacing"></a>
2807
- - [19.15](#whitespace--comma-spacing) Avoid spaces before commas and require a space after commas. eslint: [`comma-spacing`](https://eslint.org/docs/rules/comma-spacing)
2808
-
2809
- ```javascript
2810
- // bad
2811
- var foo = 1,bar = 2;
2812
- var arr = [1 , 2];
2813
-
2814
- // good
2815
- var foo = 1, bar = 2;
2816
- var arr = [1, 2];
2817
- ```
2818
-
2819
- <a name="whitespace--computed-property-spacing"></a>
2820
- - [19.16](#whitespace--computed-property-spacing) Enforce spacing inside of computed property brackets. eslint: [`computed-property-spacing`](https://eslint.org/docs/rules/computed-property-spacing)
2821
-
2822
- ```javascript
2823
- // bad
2824
- obj[foo ]
2825
- obj[ 'foo']
2826
- var x = {[ b ]: a}
2827
- obj[foo[ bar ]]
2828
-
2829
- // good
2830
- obj[foo]
2831
- obj['foo']
2832
- var x = { [b]: a }
2833
- obj[foo[bar]]
2834
- ```
2835
-
2836
- <a name="whitespace--func-call-spacing"></a>
2837
- - [19.17](#whitespace--func-call-spacing) Avoid spaces between functions and their invocations. eslint: [`func-call-spacing`](https://eslint.org/docs/rules/func-call-spacing)
2838
-
2839
- ```javascript
2840
- // bad
2841
- func ();
2842
-
2843
- func
2844
- ();
2845
-
2846
- // good
2847
- func();
2848
- ```
2849
-
2850
- <a name="whitespace--key-spacing"></a>
2851
- - [19.18](#whitespace--key-spacing) Enforce spacing between keys and values in object literal properties. eslint: [`key-spacing`](https://eslint.org/docs/rules/key-spacing)
2852
-
2853
- ```javascript
2854
- // bad
2855
- var obj = { "foo" : 42 };
2856
- var obj2 = { "foo":42 };
2857
-
2858
- // good
2859
- var obj = { "foo": 42 };
2860
- ```
2861
-
2862
- <a name="whitespace--no-trailing-spaces"></a>
2863
- - [19.19](#whitespace--no-trailing-spaces) Avoid trailing spaces at the end of lines. eslint: [`no-trailing-spaces`](https://eslint.org/docs/rules/no-trailing-spaces)
2864
-
2865
- <a name="whitespace--no-multiple-empty-lines"></a>
2866
- - [19.20](#whitespace--no-multiple-empty-lines) Avoid multiple empty lines, only allow one newline at the end of files, and avoid a newline at the beginning of files. eslint: [`no-multiple-empty-lines`](https://eslint.org/docs/rules/no-multiple-empty-lines)
2867
-
2868
- <!-- markdownlint-disable MD012 -->
2869
- ```javascript
2870
- // bad - multiple empty lines
2871
- var x = 1;
2872
-
2873
-
2874
- var y = 2;
2875
-
2876
- // bad - 2+ newlines at end of file
2877
- var x = 1;
2878
- var y = 2;
2879
-
2880
-
2881
- // bad - 1+ newline(s) at beginning of file
2882
-
2883
- var x = 1;
2884
- var y = 2;
2885
-
2886
- // good
2887
- var x = 1;
2888
- var y = 2;
2889
-
2890
- ```
2891
- <!-- markdownlint-enable MD012 -->
2892
-
2893
- **[⬆ back to top](#table-of-contents)**
2894
-
2895
- ## Commas
2896
-
2897
- <a name="commas--leading-trailing"></a><a name="19.1"></a>
2898
- - [20.1](#commas--leading-trailing) Leading commas: **Nope.** eslint: [`comma-style`](https://eslint.org/docs/rules/comma-style.html)
2899
-
2900
- ```javascript
2901
- // bad
2902
- const story = [
2903
- once
2904
- , upon
2905
- , aTime
2906
- ];
2907
-
2908
- // good
2909
- const story = [
2910
- once,
2911
- upon,
2912
- aTime,
2913
- ];
2914
-
2915
- // bad
2916
- const hero = {
2917
- firstName: 'Ada'
2918
- , lastName: 'Lovelace'
2919
- , birthYear: 1815
2920
- , superPower: 'computers'
2921
- };
2922
-
2923
- // good
2924
- const hero = {
2925
- firstName: 'Ada',
2926
- lastName: 'Lovelace',
2927
- birthYear: 1815,
2928
- superPower: 'computers',
2929
- };
2930
- ```
2931
-
2932
- <a name="commas--dangling"></a><a name="19.2"></a>
2933
- - [20.2](#commas--dangling) Additional trailing comma: **Yup.** eslint: [`comma-dangle`](https://eslint.org/docs/rules/comma-dangle.html)
2934
-
2935
- > 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](https://github.com/airbnb/javascript/blob/es5-deprecated/es5/README.md#commas) in legacy browsers.
2936
-
2937
- ```diff
2938
- // bad - git diff without trailing comma
2939
- const hero = {
2940
- firstName: 'Florence',
2941
- - lastName: 'Nightingale'
2942
- + lastName: 'Nightingale',
2943
- + inventorOf: ['coxcomb chart', 'modern nursing']
2944
- };
2945
-
2946
- // good - git diff with trailing comma
2947
- const hero = {
2948
- firstName: 'Florence',
2949
- lastName: 'Nightingale',
2950
- + inventorOf: ['coxcomb chart', 'modern nursing'],
2951
- };
2952
- ```
2953
-
2954
- ```javascript
2955
- // bad
2956
- const hero = {
2957
- firstName: 'Dana',
2958
- lastName: 'Scully'
2959
- };
2960
-
2961
- const heroes = [
2962
- 'Batman',
2963
- 'Superman'
2964
- ];
2965
-
2966
- // good
2967
- const hero = {
2968
- firstName: 'Dana',
2969
- lastName: 'Scully',
2970
- };
2971
-
2972
- const heroes = [
2973
- 'Batman',
2974
- 'Superman',
2975
- ];
2976
-
2977
- // bad
2978
- function createHero(
2979
- firstName,
2980
- lastName,
2981
- inventorOf
2982
- ) {
2983
- // does nothing
2984
- }
2985
-
2986
- // good
2987
- function createHero(
2988
- firstName,
2989
- lastName,
2990
- inventorOf,
2991
- ) {
2992
- // does nothing
2993
- }
2994
-
2995
- // good (note that a comma must not appear after a "rest" element)
2996
- function createHero(
2997
- firstName,
2998
- lastName,
2999
- inventorOf,
3000
- ...heroArgs
3001
- ) {
3002
- // does nothing
3003
- }
3004
-
3005
- // bad
3006
- createHero(
3007
- firstName,
3008
- lastName,
3009
- inventorOf
3010
- );
3011
-
3012
- // good
3013
- createHero(
3014
- firstName,
3015
- lastName,
3016
- inventorOf,
3017
- );
3018
-
3019
- // good (note that a comma must not appear after a "rest" element)
3020
- createHero(
3021
- firstName,
3022
- lastName,
3023
- inventorOf,
3024
- ...heroArgs
3025
- );
3026
- ```
3027
-
3028
- **[⬆ back to top](#table-of-contents)**
3029
-
3030
- ## Semicolons
3031
-
3032
- <a name="semicolons--required"></a><a name="20.1"></a>
3033
- - [21.1](#semicolons--required) **Yup.** eslint: [`semi`](https://eslint.org/docs/rules/semi.html)
3034
-
3035
- > Why? When JavaScript encounters a line break without a semicolon, it uses a set of rules called [Automatic Semicolon Insertion](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion) to determine whether or not it should regard that line break as the end of a statement, and (as the name implies) place a semicolon into your code before the line break if it thinks so. ASI contains a few eccentric behaviors, though, and your code will break if JavaScript misinterprets your line break. These rules will become more complicated as new features become a part of JavaScript. Explicitly terminating your statements and configuring your linter to catch missing semicolons will help prevent you from encountering issues.
3036
-
3037
- ```javascript
3038
- // bad - raises exception
3039
- const luke = {}
3040
- const leia = {}
3041
- [luke, leia].forEach((jedi) => jedi.father = 'vader')
3042
-
3043
- // bad - raises exception
3044
- const reaction = "No! That’s impossible!"
3045
- (async function meanwhileOnTheFalcon() {
3046
- // handle `leia`, `lando`, `chewie`, `r2`, `c3p0`
3047
- // ...
3048
- }())
3049
-
3050
- // bad - returns `undefined` instead of the value on the next line - always happens when `return` is on a line by itself because of ASI!
3051
- function foo() {
3052
- return
3053
- 'search your feelings, you know it to be foo'
3054
- }
3055
-
3056
- // good
3057
- const luke = {};
3058
- const leia = {};
3059
- [luke, leia].forEach((jedi) => {
3060
- jedi.father = 'vader';
3061
- });
3062
-
3063
- // good
3064
- const reaction = "No! That’s impossible!";
3065
- (async function meanwhileOnTheFalcon() {
3066
- // handle `leia`, `lando`, `chewie`, `r2`, `c3p0`
3067
- // ...
3068
- }());
3069
-
3070
- // good
3071
- function foo() {
3072
- return 'search your feelings, you know it to be foo';
3073
- }
3074
- ```
3075
-
3076
- [Read more](https://stackoverflow.com/questions/7365172/semicolon-before-self-invoking-function/7365214#7365214).
3077
-
3078
- **[⬆ back to top](#table-of-contents)**
3079
-
3080
- ## Type Casting & Coercion
3081
-
3082
- <a name="coercion--explicit"></a><a name="21.1"></a>
3083
- - [22.1](#coercion--explicit) Perform type coercion at the beginning of the statement.
3084
-
3085
- <a name="coercion--strings"></a><a name="21.2"></a>
3086
- - [22.2](#coercion--strings) Strings: eslint: [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers)
3087
-
3088
- ```javascript
3089
- // => this.reviewScore = 9;
3090
-
3091
- // bad
3092
- const totalScore = new String(this.reviewScore); // typeof totalScore is "object" not "string"
3093
-
3094
- // bad
3095
- const totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf()
3096
-
3097
- // bad
3098
- const totalScore = this.reviewScore.toString(); // isn’t guaranteed to return a string
3099
-
3100
- // good
3101
- const totalScore = String(this.reviewScore);
3102
- ```
3103
-
3104
- <a name="coercion--numbers"></a><a name="21.3"></a>
3105
- - [22.3](#coercion--numbers) Numbers: Use `Number` for type casting and `parseInt` always with a radix for parsing strings. eslint: [`radix`](https://eslint.org/docs/rules/radix) [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers)
3106
-
3107
- ```javascript
3108
- const inputValue = '4';
3109
-
3110
- // bad
3111
- const val = new Number(inputValue);
3112
-
3113
- // bad
3114
- const val = +inputValue;
3115
-
3116
- // bad
3117
- const val = inputValue >> 0;
3118
-
3119
- // bad
3120
- const val = parseInt(inputValue);
3121
-
3122
- // good
3123
- const val = Number(inputValue);
3124
-
3125
- // good
3126
- const val = parseInt(inputValue, 10);
3127
- ```
3128
-
3129
- <a name="coercion--comment-deviations"></a><a name="21.4"></a>
3130
- - [22.4](#coercion--comment-deviations) If for whatever reason you are doing something wild and `parseInt` is your bottleneck and need to use Bitshift for [performance reasons](https://jsperf.com/coercion-vs-casting/3), leave a comment explaining why and what you’re doing.
3131
-
3132
- ```javascript
3133
- // good
3134
- /**
3135
- * parseInt was the reason my code was slow.
3136
- * Bitshifting the String to coerce it to a
3137
- * Number made it a lot faster.
3138
- */
3139
- const val = inputValue >> 0;
3140
- ```
3141
-
3142
- <a name="coercion--bitwise"></a><a name="21.5"></a>
3143
- - [22.5](#coercion--bitwise) **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](https://es5.github.io/#x4.3.19), but bitshift operations always return a 32-bit integer ([source](https://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:
3144
-
3145
- ```javascript
3146
- 2147483647 >> 0; // => 2147483647
3147
- 2147483648 >> 0; // => -2147483648
3148
- 2147483649 >> 0; // => -2147483647
3149
- ```
3150
-
3151
- <a name="coercion--booleans"></a><a name="21.6"></a>
3152
- - [22.6](#coercion--booleans) Booleans: eslint: [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers)
3153
-
3154
- ```javascript
3155
- const age = 0;
3156
-
3157
- // bad
3158
- const hasAge = new Boolean(age);
3159
-
3160
- // good
3161
- const hasAge = Boolean(age);
3162
-
3163
- // best
3164
- const hasAge = !!age;
3165
- ```
3166
-
3167
- **[⬆ back to top](#table-of-contents)**
3168
-
3169
- ## Naming Conventions
3170
-
3171
- <a name="naming--descriptive"></a><a name="22.1"></a>
3172
- - [23.1](#naming--descriptive) Avoid single letter names. Be descriptive with your naming. eslint: [`id-length`](https://eslint.org/docs/rules/id-length)
3173
-
3174
- ```javascript
3175
- // bad
3176
- function q() {
3177
- // ...
3178
- }
3179
-
3180
- // good
3181
- function query() {
3182
- // ...
3183
- }
3184
- ```
3185
-
3186
- <a name="naming--camelCase"></a><a name="22.2"></a>
3187
- - [23.2](#naming--camelCase) Use camelCase when naming objects, functions, and instances. eslint: [`camelcase`](https://eslint.org/docs/rules/camelcase.html)
3188
-
3189
- ```javascript
3190
- // bad
3191
- const OBJEcttsssss = {};
3192
- const this_is_my_object = {};
3193
- function c() {}
3194
-
3195
- // good
3196
- const thisIsMyObject = {};
3197
- function thisIsMyFunction() {}
3198
- ```
3199
-
3200
- <a name="naming--PascalCase"></a><a name="22.3"></a>
3201
- - [23.3](#naming--PascalCase) Use PascalCase only when naming constructors or classes. eslint: [`new-cap`](https://eslint.org/docs/rules/new-cap.html)
3202
-
3203
- ```javascript
3204
- // bad
3205
- function user(options) {
3206
- this.name = options.name;
3207
- }
3208
-
3209
- const bad = new user({
3210
- name: 'nope',
3211
- });
3212
-
3213
- // good
3214
- class User {
3215
- constructor(options) {
3216
- this.name = options.name;
3217
- }
3218
- }
3219
-
3220
- const good = new User({
3221
- name: 'yup',
3222
- });
3223
- ```
3224
-
3225
- <a name="naming--leading-underscore"></a><a name="22.4"></a>
3226
- - [23.4](#naming--leading-underscore) Do not use trailing or leading underscores. eslint: [`no-underscore-dangle`](https://eslint.org/docs/rules/no-underscore-dangle.html)
3227
-
3228
- > Why? JavaScript does not have the concept of privacy in terms of properties or methods. Although a leading underscore is a common convention to mean “private”, in fact, these properties are fully public, and as such, are part of your public API contract. This convention might lead developers to wrongly think that a change won’t count as breaking, or that tests aren’t needed. tl;dr: if you want something to be “private”, it must not be observably present.
3229
-
3230
- ```javascript
3231
- // bad
3232
- this.__firstName__ = 'Panda';
3233
- this.firstName_ = 'Panda';
3234
- this._firstName = 'Panda';
3235
-
3236
- // good
3237
- this.firstName = 'Panda';
3238
-
3239
- // good, in environments where WeakMaps are available
3240
- // see https://kangax.github.io/compat-table/es6/#test-WeakMap
3241
- const firstNames = new WeakMap();
3242
- firstNames.set(this, 'Panda');
3243
- ```
3244
-
3245
- <a name="naming--self-this"></a><a name="22.5"></a>
3246
- - [23.5](#naming--self-this) Don’t save references to `this`. Use arrow functions or [Function#bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
3247
-
3248
- ```javascript
3249
- // bad
3250
- function foo() {
3251
- const self = this;
3252
- return function () {
3253
- console.log(self);
3254
- };
3255
- }
3256
-
3257
- // bad
3258
- function foo() {
3259
- const that = this;
3260
- return function () {
3261
- console.log(that);
3262
- };
3263
- }
3264
-
3265
- // good
3266
- function foo() {
3267
- return () => {
3268
- console.log(this);
3269
- };
3270
- }
3271
- ```
3272
-
3273
- <a name="naming--filename-matches-export"></a><a name="22.6"></a>
3274
- - [23.6](#naming--filename-matches-export) A base filename should exactly match the name of its default export.
3275
-
3276
- ```javascript
3277
- // file 1 contents
3278
- class CheckBox {
3279
- // ...
3280
- }
3281
- export default CheckBox;
3282
-
3283
- // file 2 contents
3284
- export default function fortyTwo() { return 42; }
3285
-
3286
- // file 3 contents
3287
- export default function insideDirectory() {}
3288
-
3289
- // in some other file
3290
- // bad
3291
- import CheckBox from './checkBox'; // PascalCase import/export, camelCase filename
3292
- import FortyTwo from './FortyTwo'; // PascalCase import/filename, camelCase export
3293
- import InsideDirectory from './InsideDirectory'; // PascalCase import/filename, camelCase export
3294
-
3295
- // bad
3296
- import CheckBox from './check_box'; // PascalCase import/export, snake_case filename
3297
- import forty_two from './forty_two'; // snake_case import/filename, camelCase export
3298
- import inside_directory from './inside_directory'; // snake_case import, camelCase export
3299
- import index from './inside_directory/index'; // requiring the index file explicitly
3300
- import insideDirectory from './insideDirectory/index'; // requiring the index file explicitly
3301
-
3302
- // good
3303
- import CheckBox from './CheckBox'; // PascalCase export/import/filename
3304
- import fortyTwo from './fortyTwo'; // camelCase export/import/filename
3305
- import insideDirectory from './insideDirectory'; // camelCase export/import/directory name/implicit "index"
3306
- // ^ supports both insideDirectory.js and insideDirectory/index.js
3307
- ```
3308
-
3309
- <a name="naming--camelCase-default-export"></a><a name="22.7"></a>
3310
- - [23.7](#naming--camelCase-default-export) Use camelCase when you export-default a function. Your filename should be identical to your function’s name.
3311
-
3312
- ```javascript
3313
- function makeStyleGuide() {
3314
- // ...
3315
- }
3316
-
3317
- export default makeStyleGuide;
3318
- ```
3319
-
3320
- <a name="naming--PascalCase-singleton"></a><a name="22.8"></a>
3321
- - [23.8](#naming--PascalCase-singleton) Use PascalCase when you export a constructor / class / singleton / function library / bare object.
3322
-
3323
- ```javascript
3324
- const AirbnbStyleGuide = {
3325
- es6: {
3326
- },
3327
- };
3328
-
3329
- export default AirbnbStyleGuide;
3330
- ```
3331
-
3332
- <a name="naming--Acronyms-and-Initialisms"></a>
3333
- - [23.9](#naming--Acronyms-and-Initialisms) Acronyms and initialisms should always be all uppercased, or all lowercased.
3334
-
3335
- > Why? Names are for readability, not to appease a computer algorithm.
3336
-
3337
- ```javascript
3338
- // bad
3339
- import SmsContainer from './containers/SmsContainer';
3340
-
3341
- // bad
3342
- const HttpRequests = [
3343
- // ...
3344
- ];
3345
-
3346
- // good
3347
- import SMSContainer from './containers/SMSContainer';
3348
-
3349
- // good
3350
- const HTTPRequests = [
3351
- // ...
3352
- ];
3353
-
3354
- // also good
3355
- const httpRequests = [
3356
- // ...
3357
- ];
3358
-
3359
- // best
3360
- import TextMessageContainer from './containers/TextMessageContainer';
3361
-
3362
- // best
3363
- const requests = [
3364
- // ...
3365
- ];
3366
- ```
3367
-
3368
- <a name="naming--uppercase"></a>
3369
- - [23.10](#naming--uppercase) You may optionally uppercase a constant only if it (1) is exported, (2) is a `const` (it can not be reassigned), and (3) the programmer can trust it (and its nested properties) to never change.
3370
-
3371
- > Why? This is an additional tool to assist in situations where the programmer would be unsure if a variable might ever change. UPPERCASE_VARIABLES are letting the programmer know that they can trust the variable (and its properties) not to change.
3372
- - What about all `const` variables? - This is unnecessary, so uppercasing should not be used for constants within a file. It should be used for exported constants however.
3373
- - What about exported objects? - Uppercase at the top level of export (e.g. `EXPORTED_OBJECT.key`) and maintain that all nested properties do not change.
3374
-
3375
- ```javascript
3376
- // bad
3377
- const PRIVATE_VARIABLE = 'should not be unnecessarily uppercased within a file';
3378
-
3379
- // bad
3380
- export const THING_TO_BE_CHANGED = 'should obviously not be uppercased';
3381
-
3382
- // bad
3383
- export let REASSIGNABLE_VARIABLE = 'do not use let with uppercase variables';
3384
-
3385
- // ---
3386
-
3387
- // allowed but does not supply semantic value
3388
- export const apiKey = 'SOMEKEY';
3389
-
3390
- // better in most cases
3391
- export const API_KEY = 'SOMEKEY';
3392
-
3393
- // ---
3394
-
3395
- // bad - unnecessarily uppercases key while adding no semantic value
3396
- export const MAPPING = {
3397
- KEY: 'value'
3398
- };
3399
-
3400
- // good
3401
- export const MAPPING = {
3402
- key: 'value'
3403
- };
3404
- ```
3405
-
3406
- **[⬆ back to top](#table-of-contents)**
3407
-
3408
- ## Accessors
3409
-
3410
- <a name="accessors--not-required"></a><a name="23.1"></a>
3411
- - [24.1](#accessors--not-required) Accessor functions for properties are not required.
3412
-
3413
- <a name="accessors--no-getters-setters"></a><a name="23.2"></a>
3414
- - [24.2](#accessors--no-getters-setters) Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use `getVal()` and `setVal('hello')`.
3415
-
3416
- ```javascript
3417
- // bad
3418
- class Dragon {
3419
- get age() {
3420
- // ...
3421
- }
3422
-
3423
- set age(value) {
3424
- // ...
3425
- }
3426
- }
3427
-
3428
- // good
3429
- class Dragon {
3430
- getAge() {
3431
- // ...
3432
- }
3433
-
3434
- setAge(value) {
3435
- // ...
3436
- }
3437
- }
3438
- ```
3439
-
3440
- <a name="accessors--boolean-prefix"></a><a name="23.3"></a>
3441
- - [24.3](#accessors--boolean-prefix) If the property/method is a `boolean`, use `isVal()` or `hasVal()`.
3442
-
3443
- ```javascript
3444
- // bad
3445
- if (!dragon.age()) {
3446
- return false;
3447
- }
3448
-
3449
- // good
3450
- if (!dragon.hasAge()) {
3451
- return false;
3452
- }
3453
- ```
3454
-
3455
- <a name="accessors--consistent"></a><a name="23.4"></a>
3456
- - [24.4](#accessors--consistent) It’s okay to create `get()` and `set()` functions, but be consistent.
3457
-
3458
- ```javascript
3459
- class Jedi {
3460
- constructor(options = {}) {
3461
- const lightsaber = options.lightsaber || 'blue';
3462
- this.set('lightsaber', lightsaber);
3463
- }
3464
-
3465
- set(key, val) {
3466
- this[key] = val;
3467
- }
3468
-
3469
- get(key) {
3470
- return this[key];
3471
- }
3472
- }
3473
- ```
3474
-
3475
- **[⬆ back to top](#table-of-contents)**
3476
-
3477
- ## Events
3478
-
3479
- <a name="events--hash"></a><a name="24.1"></a>
3480
- - [25.1](#events--hash) When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass an object literal (also known as 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:
3481
-
3482
- ```javascript
3483
- // bad
3484
- $(this).trigger('listingUpdated', listing.id);
3485
-
3486
- // ...
3487
-
3488
- $(this).on('listingUpdated', (e, listingID) => {
3489
- // do something with listingID
3490
- });
3491
- ```
3492
-
3493
- prefer:
3494
-
3495
- ```javascript
3496
- // good
3497
- $(this).trigger('listingUpdated', { listingID: listing.id });
3498
-
3499
- // ...
3500
-
3501
- $(this).on('listingUpdated', (e, data) => {
3502
- // do something with data.listingID
3503
- });
3504
- ```
3505
-
3506
- **[⬆ back to top](#table-of-contents)**
3507
-
3508
- ## jQuery
3509
-
3510
- <a name="jquery--dollar-prefix"></a><a name="25.1"></a>
3511
- - [26.1](#jquery--dollar-prefix) Prefix jQuery object variables with a `$`.
3512
-
3513
- ```javascript
3514
- // bad
3515
- const sidebar = $('.sidebar');
3516
-
3517
- // good
3518
- const $sidebar = $('.sidebar');
3519
-
3520
- // good
3521
- const $sidebarBtn = $('.sidebar-btn');
3522
- ```
3523
-
3524
- <a name="jquery--cache"></a><a name="25.2"></a>
3525
- - [26.2](#jquery--cache) Cache jQuery lookups.
3526
-
3527
- ```javascript
3528
- // bad
3529
- function setSidebar() {
3530
- $('.sidebar').hide();
3531
-
3532
- // ...
3533
-
3534
- $('.sidebar').css({
3535
- 'background-color': 'pink',
3536
- });
3537
- }
3538
-
3539
- // good
3540
- function setSidebar() {
3541
- const $sidebar = $('.sidebar');
3542
- $sidebar.hide();
3543
-
3544
- // ...
3545
-
3546
- $sidebar.css({
3547
- 'background-color': 'pink',
3548
- });
3549
- }
3550
- ```
3551
-
3552
- <a name="jquery--queries"></a><a name="25.3"></a>
3553
- - [26.3](#jquery--queries) For DOM queries use Cascading `$('.sidebar ul')` or parent > child `$('.sidebar > ul')`. [jsPerf](http://jsperf.com/jquery-find-vs-context-sel/16)
3554
-
3555
- <a name="jquery--find"></a><a name="25.4"></a>
3556
- - [26.4](#jquery--find) Use `find` with scoped jQuery object queries.
3557
-
3558
- ```javascript
3559
- // bad
3560
- $('ul', '.sidebar').hide();
3561
-
3562
- // bad
3563
- $('.sidebar').find('ul').hide();
3564
-
3565
- // good
3566
- $('.sidebar ul').hide();
3567
-
3568
- // good
3569
- $('.sidebar > ul').hide();
3570
-
3571
- // good
3572
- $sidebar.find('ul').hide();
3573
- ```
3574
-
3575
- **[⬆ back to top](#table-of-contents)**
3576
-
3577
- ## ECMAScript 5 Compatibility
3578
-
3579
- <a name="es5-compat--kangax"></a><a name="26.1"></a>
3580
- - [27.1](#es5-compat--kangax) Refer to [Kangax](https://twitter.com/kangax/)’s ES5 [compatibility table](https://kangax.github.io/es5-compat-table/).
3581
-
3582
- **[⬆ back to top](#table-of-contents)**
3583
-
3584
- <a name="ecmascript-6-styles"></a>
3585
- ## ECMAScript 6+ (ES 2015+) Styles
3586
-
3587
- <a name="es6-styles"></a><a name="27.1"></a>
3588
- - [28.1](#es6-styles) This is a collection of links to the various ES6+ features.
3589
-
3590
- 1. [Arrow Functions](#arrow-functions)
3591
- 1. [Classes](#classes--constructors)
3592
- 1. [Object Shorthand](#es6-object-shorthand)
3593
- 1. [Object Concise](#es6-object-concise)
3594
- 1. [Object Computed Properties](#es6-computed-properties)
3595
- 1. [Template Strings](#es6-template-literals)
3596
- 1. [Destructuring](#destructuring)
3597
- 1. [Default Parameters](#es6-default-parameters)
3598
- 1. [Rest](#es6-rest)
3599
- 1. [Array Spreads](#es6-array-spreads)
3600
- 1. [Let and Const](#references)
3601
- 1. [Exponentiation Operator](#es2016-properties--exponentiation-operator)
3602
- 1. [Iterators and Generators](#iterators-and-generators)
3603
- 1. [Modules](#modules)
3604
-
3605
- <a name="tc39-proposals"></a>
3606
- - [28.2](#tc39-proposals) Do not use [TC39 proposals](https://github.com/tc39/proposals) that have not reached stage 3.
3607
-
3608
- > Why? [They are not finalized](https://tc39.github.io/process-document/), and they are subject to change or to be withdrawn entirely. We want to use JavaScript, and proposals are not JavaScript yet.
3609
-
3610
- **[⬆ back to top](#table-of-contents)**
3611
-
3612
- ## Standard Library
3613
-
3614
- The [Standard Library](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects)
3615
- contains utilities that are functionally broken but remain for legacy reasons.
3616
-
3617
- <a name="standard-library--isnan"></a>
3618
- - [29.1](#standard-library--isnan) Use `Number.isNaN` instead of global `isNaN`.
3619
- eslint: [`no-restricted-globals`](https://eslint.org/docs/rules/no-restricted-globals)
3620
-
3621
- > Why? The global `isNaN` coerces non-numbers to numbers, returning true for anything that coerces to NaN.
3622
- > If this behavior is desired, make it explicit.
3623
-
3624
- ```javascript
3625
- // bad
3626
- isNaN('1.2'); // false
3627
- isNaN('1.2.3'); // true
3628
-
3629
- // good
3630
- Number.isNaN('1.2.3'); // false
3631
- Number.isNaN(Number('1.2.3')); // true
3632
- ```
3633
-
3634
- <a name="standard-library--isfinite"></a>
3635
- - [29.2](#standard-library--isfinite) Use `Number.isFinite` instead of global `isFinite`.
3636
- eslint: [`no-restricted-globals`](https://eslint.org/docs/rules/no-restricted-globals)
3637
-
3638
- > Why? The global `isFinite` coerces non-numbers to numbers, returning true for anything that coerces to a finite number.
3639
- > If this behavior is desired, make it explicit.
3640
-
3641
- ```javascript
3642
- // bad
3643
- isFinite('2e3'); // true
3644
-
3645
- // good
3646
- Number.isFinite('2e3'); // false
3647
- Number.isFinite(parseInt('2e3', 10)); // true
3648
- ```
3649
-
3650
- **[⬆ back to top](#table-of-contents)**
3651
-
3652
- ## Testing
3653
-
3654
- <a name="testing--yup"></a><a name="28.1"></a>
3655
- - [30.1](#testing--yup) **Yup.**
3656
-
3657
- ```javascript
3658
- function foo() {
3659
- return true;
3660
- }
3661
- ```
3662
-
3663
- <a name="testing--for-real"></a><a name="28.2"></a>
3664
- - [30.2](#testing--for-real) **No, but seriously**:
3665
- - Whichever testing framework you use, you should be writing tests!
3666
- - Strive to write many small pure functions, and minimize where mutations occur.
3667
- - Be cautious about stubs and mocks - they can make your tests more brittle.
3668
- - We primarily use [`mocha`](https://www.npmjs.com/package/mocha) and [`jest`](https://www.npmjs.com/package/jest) at Airbnb. [`tape`](https://www.npmjs.com/package/tape) is also used occasionally for small, separate modules.
3669
- - 100% test coverage is a good goal to strive for, even if it’s not always practical to reach it.
3670
- - Whenever you fix a bug, _write a regression test_. A bug fixed without a regression test is almost certainly going to break again in the future.
3671
-
3672
- **[⬆ back to top](#table-of-contents)**
3673
-
3674
- ## Performance
3675
-
3676
- - [On Layout & Web Performance](https://www.kellegous.com/j/2013/01/26/layout-performance/)
3677
- - [String vs Array Concat](https://jsperf.com/string-vs-array-concat/2)
3678
- - [Try/Catch Cost In a Loop](https://jsperf.com/try-catch-in-loop-cost/12)
3679
- - [Bang Function](https://jsperf.com/bang-function)
3680
- - [jQuery Find vs Context, Selector](https://jsperf.com/jquery-find-vs-context-sel/164)
3681
- - [innerHTML vs textContent for script text](https://jsperf.com/innerhtml-vs-textcontent-for-script-text)
3682
- - [Long String Concatenation](https://jsperf.com/ya-string-concat/38)
3683
- - [Are JavaScript functions like `map()`, `reduce()`, and `filter()` optimized for traversing arrays?](https://www.quora.com/JavaScript-programming-language-Are-Javascript-functions-like-map-reduce-and-filter-already-optimized-for-traversing-array/answer/Quildreen-Motta)
3684
- - Loading...
3685
-
3686
- **[⬆ back to top](#table-of-contents)**
3687
-
3688
- ## Resources
3689
-
3690
- **Learning ES6+**
3691
-
3692
- - [Latest ECMA spec](https://tc39.github.io/ecma262/)
3693
- - [ExploringJS](http://exploringjs.com/)
3694
- - [ES6 Compatibility Table](https://kangax.github.io/compat-table/es6/)
3695
- - [Comprehensive Overview of ES6 Features](http://es6-features.org/)
3696
-
3697
- **Read This**
3698
-
3699
- - [Standard ECMA-262](http://www.ecma-international.org/ecma-262/6.0/index.html)
3700
-
3701
- **Tools**
3702
-
3703
- - Code Style Linters
3704
- - [ESlint](https://eslint.org/) - [Airbnb Style .eslintrc](https://github.com/airbnb/javascript/blob/master/linters/.eslintrc)
3705
- - [JSHint](http://jshint.com/) - [Airbnb Style .jshintrc](https://github.com/airbnb/javascript/blob/master/linters/.jshintrc)
3706
- - Neutrino Preset - [@neutrinojs/airbnb](https://neutrinojs.org/packages/airbnb/)
3707
-
3708
- **Other Style Guides**
3709
-
3710
- - [Google JavaScript Style Guide](https://google.github.io/styleguide/jsguide.html)
3711
- - [Google JavaScript Style Guide (Old)](https://google.github.io/styleguide/javascriptguide.xml)
3712
- - [jQuery Core Style Guidelines](https://contribute.jquery.org/style-guide/js/)
3713
- - [Principles of Writing Consistent, Idiomatic JavaScript](https://github.com/rwaldron/idiomatic.js)
3714
- - [StandardJS](https://standardjs.com)
3715
-
3716
- **Other Styles**
3717
-
3718
- - [Naming this in nested functions](https://gist.github.com/cjohansen/4135065) - Christian Johansen
3719
- - [Conditional Callbacks](https://github.com/airbnb/javascript/issues/52) - Ross Allen
3720
- - [Popular JavaScript Coding Conventions on GitHub](http://sideeffect.kr/popularconvention/#javascript) - JeongHoon Byun
3721
- - [Multiple var statements in JavaScript, not superfluous](http://benalman.com/news/2012/05/multiple-var-statements-javascript/) - Ben Alman
3722
-
3723
- **Further Reading**
3724
-
3725
- - [Understanding JavaScript Closures](https://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/) - Angus Croll
3726
- - [Basic JavaScript for the impatient programmer](http://www.2ality.com/2013/06/basic-javascript.html) - Dr. Axel Rauschmayer
3727
- - [You Might Not Need jQuery](http://youmightnotneedjquery.com/) - Zack Bloom & Adam Schwartz
3728
- - [ES6 Features](https://github.com/lukehoban/es6features) - Luke Hoban
3729
- - [Frontend Guidelines](https://github.com/bendc/frontend-guidelines) - Benjamin De Cock
3730
-
3731
- **Books**
3732
-
3733
- - [JavaScript: The Good Parts](https://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) - Douglas Crockford
3734
- - [JavaScript Patterns](https://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752) - Stoyan Stefanov
3735
- - [Pro JavaScript Design Patterns](https://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X) - Ross Harmes and Dustin Diaz
3736
- - [High Performance Web Sites: Essential Knowledge for Front-End Engineers](https://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309) - Steve Souders
3737
- - [Maintainable JavaScript](https://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680) - Nicholas C. Zakas
3738
- - [JavaScript Web Applications](https://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X) - Alex MacCaw
3739
- - [Pro JavaScript Techniques](https://www.amazon.com/Pro-JavaScript-Techniques-John-Resig/dp/1590597273) - John Resig
3740
- - [Smashing Node.js: JavaScript Everywhere](https://www.amazon.com/Smashing-Node-js-JavaScript-Everywhere-Magazine/dp/1119962595) - Guillermo Rauch
3741
- - [Secrets of the JavaScript Ninja](https://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/193398869X) - John Resig and Bear Bibeault
3742
- - [Human JavaScript](http://humanjavascript.com/) - Henrik Joreteg
3743
- - [Superhero.js](http://superherojs.com/) - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy
3744
- - [JSBooks](http://jsbooks.revolunet.com/) - Julien Bouquillon
3745
- - [Third Party JavaScript](https://www.manning.com/books/third-party-javascript) - Ben Vinegar and Anton Kovalyov
3746
- - [Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript](http://amzn.com/0321812182) - David Herman
3747
- - [Eloquent JavaScript](http://eloquentjavascript.net/) - Marijn Haverbeke
3748
- - [You Don’t Know JS: ES6 & Beyond](http://shop.oreilly.com/product/0636920033769.do) - Kyle Simpson
3749
-
3750
- **Blogs**
3751
-
3752
- - [JavaScript Weekly](http://javascriptweekly.com/)
3753
- - [JavaScript, JavaScript...](https://javascriptweblog.wordpress.com/)
3754
- - [Bocoup Weblog](https://bocoup.com/weblog)
3755
- - [Adequately Good](http://www.adequatelygood.com/)
3756
- - [NCZOnline](https://www.nczonline.net/)
3757
- - [Perfection Kills](http://perfectionkills.com/)
3758
- - [Ben Alman](http://benalman.com/)
3759
- - [Dmitry Baranovskiy](http://dmitry.baranovskiy.com/)
3760
- - [nettuts](http://code.tutsplus.com/?s=javascript)
3761
-
3762
- **Podcasts**
3763
-
3764
- - [JavaScript Air](https://javascriptair.com/)
3765
- - [JavaScript Jabber](https://devchat.tv/js-jabber/)
3766
-
3767
- **[⬆ back to top](#table-of-contents)**
3768
-
3769
- ## Contributors
3770
-
3771
- This project is forked from airbnb's JavaScript Guide.
3772
-
3773
- - [View Base Project](https://github.com/airbnb/javascript)
3774
- - [View Contributors](https://github.com/airbnb/javascript/graphs/contributors)
3775
-
3776
- ## License
3777
-
3778
- MIT License, for further details, please see [LICENSE](LICENSE) file
3779
-
3780
- **[⬆ back to top](#table-of-contents)**
3781
-
3782
- ## To Support
3783
-
3784
- [Visit my patreon profile at patreon.com/eserozvataf](https://www.patreon.com/eserozvataf)
3785
-
3786
- **[⬆ back to top](#table-of-contents)**
3787
-
3788
- [npm-image]: https://img.shields.io/npm/v/eser.svg?style=flat-square
3789
- [npm-url]: https://www.npmjs.com/package/eser
3790
- [download-image]: https://img.shields.io/npm/dt/eser.svg?style=flat-square
3791
- [dep-image]: https://img.shields.io/david/eserozvataf/eser.svg?style=flat-square
3792
- [dep-url]: https://github.com/eserozvataf/eser
3793
- [license-image]: https://img.shields.io/npm/l/eser.svg?style=flat-square
3794
- [license-url]: https://github.com/eserozvataf/eser/blob/master/LICENSE