-
Notifications
You must be signed in to change notification settings - Fork 3
/
file.airbnb_javascript_style_guide.html
4224 lines (3808 loc) · 160 KB
/
file.airbnb_javascript_style_guide.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, user-scalable=no'>
<meta name='apple-touch-fullscreen' content='yes'>
<meta name='apple-mobile-web-app-capable' content='yes'>
<meta name='apple-mobile-web-app-status-bar-style' content='rgba(228,228,228,1.0)'>
<title>Airbnb JavaScript Style Guide</title>
<link rel='stylesheet' type='text/css' href='css/y_fonts.css' />
<link rel='stylesheet' type='text/css' href='css/highlight.github.css' />
<link rel='stylesheet' type='text/css' href='css/y_style.css' />
<link rel='stylesheet' type='text/css' href='css/y_list.css' />
<link rel='stylesheet' type='text/css' href='css/y_color.css' />
<script type='text/javascript'>
var pathId = "airbnb_javascript_style_guide",
relpath = '';
var t2Info = {
CSEP: '.',
ISEP: '#',
NSEP: '::'
};
</script>
<script type='text/javascript' charset='utf-8' src='js/highlight.pack.js'></script>
<script type='text/javascript' charset='utf-8' src='js/y_app.js'></script>
</head>
<body>
<svg id='y_wait' class viewBox='0 0 90 90'></svg>
<div id='settings' class='hidden'></div>
<div id='y_list' class='d h'>
<header id='list_header'></header>
<nav id= 'list_nav' class='y_nav l_nav'>
<ul id='list_items'></ul>
</nav>
</div>
<div id='y_toc' class='f h'>
<header id='toc_header'></header>
<nav id= 'toc_nav' class='y_nav t_nav'>
<ol id='toc_items'></ol>
</nav>
</div>
<div id='y_main' tabindex='-1'>
<header id='y_header'>
<div id='y_menu'>
<a id='home_no_xhr' href='/'>Home</a> »
<a href='_index.html'>Index</a> »
<span class='title'><a id='t2_doc_top' href='#'>Airbnb JavaScript Style Guide ▲</a></span>
</div>
<a id='list_href' href="file_list.html"></a>
<div id='y_measure_em' class='y_measure'></div>
<div id='y_measure_vh' class='y_measure'></div>
<span id='y_measure_50pre' class='y_measure'><code>123456789_123456789_123456789_123456789_123456789_</code></span>
</header>
<div id='content' class='file'>
<h1>Airbnb JavaScript Style Guide() {<span style='font-size: 1rem'> Rev: 2021-12-25 34b5bc39f</span></h1>
<p><em>A mostly reasonable approach to JavaScript</em></p>
<blockquote>
<p><strong>Note</strong>: this guide assumes you are using <a href="https://babeljs.io">Babel</a>, and requires that you use <a href="https://npmjs.com/babel-preset-airbnb">babel-preset-airbnb</a> or the equivalent. It also assumes you are installing shims/polyfills in your app, with <a href="https://npmjs.com/airbnb-browser-shims">airbnb-browser-shims</a> or the equivalent.</p>
</blockquote>
<p><a href="https://www.npmjs.com/package/eslint-config-airbnb"><img src="https://img.shields.io/npm/dm/eslint-config-airbnb.svg" alt="Downloads" /></a>
<a href="https://www.npmjs.com/package/eslint-config-airbnb-base"><img src="https://img.shields.io/npm/dm/eslint-config-airbnb-base.svg" alt="Downloads" /></a>
<a href="https://gitter.im/airbnb/javascript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge"><img src="https://badges.gitter.im/Join%20Chat.svg" alt="Gitter" /></a></p>
<p>This guide is available in other languages too. See <a href="#translation">Translation</a></p>
<p>Other Style Guides</p>
<ul>
<li><a href="https://github.com/airbnb/javascript/tree/es5-deprecated/es5" target="_parent" title="ES5 (Deprecated)">ES5 (Deprecated)</a></li>
<li><a href="react/">React</a></li>
<li><a href="css-in-javascript/">CSS-in-JavaScript</a></li>
<li><a href="https://github.com/airbnb/css" target="_parent" title="CSS &amp; Sass">CSS & Sass</a></li>
<li><a href="https://github.com/airbnb/ruby" target="_parent" title="Ruby">Ruby</a></li>
</ul>
<h2>Table of Contents</h2>
<ol style='columns: 2;'>
<li><a href="#types">Types</a></li>
<li><a href="#references">References</a></li>
<li><a href="#objects">Objects</a></li>
<li><a href="#arrays">Arrays</a></li>
<li><a href="#destructuring">Destructuring</a></li>
<li><a href="#strings">Strings</a></li>
<li><a href="#functions">Functions</a></li>
<li><a href="#arrow-functions">Arrow Functions</a></li>
<li><a href="#classes--constructors">Classes & Constructors</a></li>
<li><a href="#modules">Modules</a></li>
<li><a href="#iterators-and-generators">Iterators and Generators</a></li>
<li><a href="#properties">Properties</a></li>
<li><a href="#variables">Variables</a></li>
<li><a href="#hoisting">Hoisting</a></li>
<li><a href="#comparison-operators--equality">Comparison Operators & Equality</a></li>
<li><a href="#blocks">Blocks</a></li>
<li><a href="#control-statements">Control Statements</a></li>
<li><a href="#comments">Comments</a></li>
<li><a href="#whitespace">Whitespace</a></li>
<li><a href="#commas">Commas</a></li>
<li><a href="#semicolons">Semicolons</a></li>
<li><a href="#type-casting--coercion">Type Casting & Coercion</a></li>
<li><a href="#naming-conventions">Naming Conventions</a></li>
<li><a href="#accessors">Accessors</a></li>
<li><a href="#events">Events</a></li>
<li><a href="#jquery">jQuery</a></li>
<li><a href="#ecmascript-5-compatibility">ECMAScript 5 Compatibility</a></li>
<li><a href="#ecmascript-6-es-2015-styles">ECMAScript 6+ (ES 2015+) Styles</a></li>
<li><a href="#standard-library">Standard Library</a></li>
<li><a href="#testing">Testing</a></li>
<li><a href="#performance">Performance</a></li>
<li><a href="#resources">Resources</a></li>
<li><a href="#in-the-wild">In the Wild</a></li>
<li><a href="#translation">Translation</a></li>
<li><a href="#the-javascript-style-guide-guide">The JavaScript Style Guide Guide</a></li>
<li><a href="#chat-with-us-about-javascript">Chat With Us About JavaScript</a></li>
<li><a href="#contributors">Contributors</a></li>
<li><a href="#license">License</a></li>
<li><a href="#amendments">Amendments</a></li>
</ol>
<h2>Types</h2>
<p><a name="types--primitives"></a><a name="1.1"></a></p>
<ul>
<li>
<p><a href="#types--primitives">1.1</a> <strong>Primitives</strong>: When you access a primitive type you work directly on its value.</p>
<ul>
<li><code>string</code></li>
<li><code>number</code></li>
<li><code>boolean</code></li>
<li><code>null</code></li>
<li><code>undefined</code></li>
<li><code>symbol</code></li>
<li><code>bigint</code></li>
</ul>
<pre class="code javascript"><code class="javascript">const foo = 1;
let bar = foo;
bar = 9;
console.log(foo, bar); // => 1, 9
</code></pre>
<ul>
<li>Symbols and BigInts cannot be faithfully polyfilled, so they should not be used when targeting browsers/environments that don’t support them natively.</li>
</ul>
</li>
</ul>
<p><a name="types--complex"></a><a name="1.2"></a></p>
<ul>
<li>
<p><a href="#types--complex">1.2</a> <strong>Complex</strong>: When you access a complex type you work on a reference to its value.</p>
<ul>
<li><code>object</code></li>
<li><code>array</code></li>
<li><code>function</code></li>
</ul>
<pre class="code javascript"><code class="javascript">const foo = [1, 2];
const bar = foo;
bar[0] = 9;
console.log(foo[0], bar[0]); // => 9, 9
</code></pre>
</li>
</ul>
<p><strong><a href="#table-of-contents">▲ back to top</a></strong></p>
<h2>References</h2>
<p><a name="references--prefer-const"></a><a name="2.1"></a></p>
<ul>
<li>
<p><a href="#references--prefer-const">2.1</a> Use <code>const</code> for all of your references; avoid using <code>var</code>. eslint: <a href="https://eslint.org/docs/rules/prefer-const.html" target="_parent" title="prefer-const">prefer-const</a>, <a href="https://eslint.org/docs/rules/no-const-assign.html" target="_parent" title="no-const-assign">no-const-assign</a></p>
<blockquote>
<p>Why? This ensures that you can’t reassign your references, which can lead to bugs and difficult to comprehend code.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
var a = 1;
var b = 2;
// good
const a = 1;
const b = 2;
</code></pre>
</li>
</ul>
<p><a name="references--disallow-var"></a><a name="2.2"></a></p>
<ul>
<li>
<p><a href="#references--disallow-var">2.2</a> If you must reassign references, use <code>let</code> instead of <code>var</code>. eslint: <a href="https://eslint.org/docs/rules/no-var.html" target="_parent" title="no-var">no-var</a></p>
<blockquote>
<p>Why? <code>let</code> is block-scoped rather than function-scoped like <code>var</code>.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
var count = 1;
if (true) {
count += 1;
}
// good, use the let.
let count = 1;
if (true) {
count += 1;
}
</code></pre>
</li>
</ul>
<p><a name="references--block-scope"></a><a name="2.3"></a></p>
<ul>
<li>
<p><a href="#references--block-scope">2.3</a> Note that both <code>let</code> and <code>const</code> are block-scoped, whereas <code>var</code> is function-scoped.</p>
<pre class="code javascript"><code class="javascript">// const and let only exist in the blocks they are defined in.
{
let a = 1;
const b = 1;
var c = 1;
}
console.log(a); // ReferenceError
console.log(b); // ReferenceError
console.log(c); // Prints 1
</code></pre>
<p>In the above code, you can see that referencing <code>a</code> and <code>b</code> will produce a ReferenceError, while <code>c</code> contains the number. This is because <code>a</code> and <code>b</code> are block scoped, while <code>c</code> is scoped to the containing function.</p>
</li>
</ul>
<p><strong><a href="#table-of-contents">▲ back to top</a></strong></p>
<h2>Objects</h2>
<p><a name="objects--no-new"></a><a name="3.1"></a></p>
<ul>
<li>
<p><a href="#objects--no-new">3.1</a> Use the literal syntax for object creation. eslint: <a href="https://eslint.org/docs/rules/no-new-object.html" target="_parent" title="no-new-object">no-new-object</a></p>
<pre class="code javascript"><code class="javascript">// bad
const item = new Object();
// good
const item = {};
</code></pre>
</li>
</ul>
<p><a name="es6-computed-properties"></a><a name="3.4"></a></p>
<ul>
<li>
<p><a href="#es6-computed-properties">3.2</a> Use computed property names when creating objects with dynamic property names.</p>
<blockquote>
<p>Why? They allow you to define all the properties of an object in one place.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">function getKey(k) {
return `a key named ${k}`;
}
// bad
const obj = {
id: 5,
name: 'San Francisco',
};
obj[getKey('enabled')] = true;
// good
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};
</code></pre>
</li>
</ul>
<p><a name="es6-object-shorthand"></a><a name="3.5"></a></p>
<ul>
<li>
<p><a href="#es6-object-shorthand">3.3</a> Use object method shorthand. eslint: <a href="https://eslint.org/docs/rules/object-shorthand.html" target="_parent" title="object-shorthand">object-shorthand</a></p>
<pre class="code javascript"><code class="javascript">// bad
const atom = {
value: 1,
addValue: function (value) {
return atom.value + value;
},
};
// good
const atom = {
value: 1,
addValue(value) {
return atom.value + value;
},
};
</code></pre>
</li>
</ul>
<p><a name="es6-object-concise"></a><a name="3.6"></a></p>
<ul>
<li>
<p><a href="#es6-object-concise">3.4</a> Use property value shorthand. eslint: <a href="https://eslint.org/docs/rules/object-shorthand.html" target="_parent" title="object-shorthand">object-shorthand</a></p>
<blockquote>
<p>Why? It is shorter and descriptive.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
lukeSkywalker: lukeSkywalker,
};
// good
const obj = {
lukeSkywalker,
};
</code></pre>
</li>
</ul>
<p><a name="objects--grouped-shorthand"></a><a name="3.7"></a></p>
<ul>
<li>
<p><a href="#objects--grouped-shorthand">3.5</a> Group your shorthand properties at the beginning of your object declaration.</p>
<blockquote>
<p>Why? It’s easier to tell which properties are using the shorthand.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';
// bad
const obj = {
episodeOne: 1,
twoJediWalkIntoACantina: 2,
lukeSkywalker,
episodeThree: 3,
mayTheFourth: 4,
anakinSkywalker,
};
// good
const obj = {
lukeSkywalker,
anakinSkywalker,
episodeOne: 1,
twoJediWalkIntoACantina: 2,
episodeThree: 3,
mayTheFourth: 4,
};
</code></pre>
</li>
</ul>
<p><a name="objects--quoted-props"></a><a name="3.8"></a></p>
<ul>
<li>
<p><a href="#objects--quoted-props">3.6</a> Only quote properties that are invalid identifiers. eslint: <a href="https://eslint.org/docs/rules/quote-props.html" target="_parent" title="quote-props">quote-props</a></p>
<blockquote>
<p>Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
const bad = {
'foo': 3,
'bar': 4,
'data-blah': 5,
};
// good
const good = {
foo: 3,
bar: 4,
'data-blah': 5,
};
</code></pre>
</li>
</ul>
<p><a name="objects--prototype-builtins"></a></p>
<ul>
<li>
<p><a href="#objects--prototype-builtins">3.7</a> Do not call <code>Object.prototype</code> methods directly, such as <code>hasOwnProperty</code>, <code>propertyIsEnumerable</code>, and <code>isPrototypeOf</code>. eslint: <a href="https://eslint.org/docs/rules/no-prototype-builtins" target="_parent" title="no-prototype-builtins">no-prototype-builtins</a></p>
<blockquote>
<p>Why? These methods may be shadowed by properties on the object in question - consider <code>{ hasOwnProperty: false }</code> - or, the object may be a null object (<code>Object.create(null)</code>).</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
console.log(object.hasOwnProperty(key));
// good
console.log(Object.prototype.hasOwnProperty.call(object, key));
// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
console.log(has.call(object, key));
/* or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));
</code></pre>
</li>
</ul>
<p><a name="objects--rest-spread"></a></p>
<ul>
<li>
<p><a href="#objects--rest-spread">3.8</a> Prefer the object spread syntax over <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign" target="_parent" title="Object.assign">Object.assign</a> to shallow-copy objects. Use the object rest parameter syntax to get a new object with certain properties omitted. eslint: <a href="https://eslint.org/docs/rules/prefer-object-spread" target="_parent" title="prefer-object-spread">prefer-object-spread</a></p>
<pre class="code javascript"><code class="javascript">// very bad
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ
delete copy.a; // so does this
// bad
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }
// good
const original = { a: 1, b: 2 };
const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }
const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
</code></pre>
</li>
</ul>
<p><strong><a href="#table-of-contents">▲ back to top</a></strong></p>
<h2>Arrays</h2>
<p><a name="arrays--literals"></a><a name="4.1"></a></p>
<ul>
<li>
<p><a href="#arrays--literals">4.1</a> Use the literal syntax for array creation. eslint: <a href="https://eslint.org/docs/rules/no-array-constructor.html" target="_parent" title="no-array-constructor">no-array-constructor</a></p>
<pre class="code javascript"><code class="javascript">// bad
const items = new Array();
// good
const items = [];
</code></pre>
</li>
</ul>
<p><a name="arrays--push"></a><a name="4.2"></a></p>
<ul>
<li>
<p><a href="#arrays--push">4.2</a> Use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push" target="_parent" title="Array#push">Array#push</a> instead of direct assignment to add items to an array.</p>
<pre class="code javascript"><code class="javascript">const someStack = [];
// bad
someStack[someStack.length] = 'abracadabra';
// good
someStack.push('abracadabra');
</code></pre>
</li>
</ul>
<p><a name="es6-array-spreads"></a><a name="4.3"></a></p>
<ul>
<li>
<p><a href="#es6-array-spreads">4.3</a> Use array spreads <code>...</code> to copy arrays.</p>
<pre class="code javascript"><code class="javascript">// bad
const len = items.length;
const itemsCopy = [];
let i;
for (i = 0; i < len; i += 1) {
itemsCopy[i] = items[i];
}
// good
const itemsCopy = [...items];
</code></pre>
</li>
</ul>
<p><a name="arrays--from"></a>
<a name="arrays--from-iterable"></a><a name="4.4"></a></p>
<ul>
<li>
<p><a href="#arrays--from-iterable">4.4</a> To convert an iterable object to an array, use spreads <code>...</code> instead of <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from" target="_parent" title="Array.from">Array.from</a>.</p>
<pre class="code javascript"><code class="javascript">const foo = document.querySelectorAll('.foo');
// good
const nodes = Array.from(foo);
// best
const nodes = [...foo];
</code></pre>
</li>
</ul>
<p><a name="arrays--from-array-like"></a></p>
<ul>
<li>
<p><a href="#arrays--from-array-like">4.5</a> Use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from" target="_parent" title="Array.from">Array.from</a> for converting an array-like object to an array.</p>
<pre class="code javascript"><code class="javascript">const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };
// bad
const arr = Array.prototype.slice.call(arrLike);
// good
const arr = Array.from(arrLike);
</code></pre>
</li>
</ul>
<p><a name="arrays--mapping"></a></p>
<ul>
<li>
<p><a href="#arrays--mapping">4.6</a> Use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from" target="_parent" title="Array.from">Array.from</a> instead of spread <code>...</code> for mapping over iterables, because it avoids creating an intermediate array.</p>
<pre class="code javascript"><code class="javascript">// bad
const baz = [...foo].map(bar);
// good
const baz = Array.from(foo, bar);
</code></pre>
</li>
</ul>
<p><a name="arrays--callback-return"></a><a name="4.5"></a></p>
<ul>
<li>
<p><a href="#arrays--callback-return">4.7</a> 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 <a href="#arrows--implicit-return">8.2</a>. eslint: <a href="https://eslint.org/docs/rules/array-callback-return" target="_parent" title="array-callback-return">array-callback-return</a></p>
<pre class="code javascript"><code class="javascript">// good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
// good
[1, 2, 3].map((x) => x + 1);
// bad - no returned value means `acc` becomes undefined after the first iteration
[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
const flatten = acc.concat(item);
});
// good
[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
const flatten = acc.concat(item);
return flatten;
});
// bad
inbox.filter((msg) => {
const { subject, author } = msg;
if (subject === 'Mockingbird') {
return author === 'Harper Lee';
} else {
return false;
}
});
// good
inbox.filter((msg) => {
const { subject, author } = msg;
if (subject === 'Mockingbird') {
return author === 'Harper Lee';
}
return false;
});
</code></pre>
</li>
</ul>
<p><a name="arrays--bracket-newline"></a></p>
<ul>
<li>
<p><a href="#arrays--bracket-newline">4.8</a> Use line breaks after open and before close array brackets if an array has multiple lines</p>
<pre class="code javascript"><code class="javascript">// bad
const arr = [
[0, 1], [2, 3], [4, 5],
];
const objectInArray = [{
id: 1,
}, {
id: 2,
}];
const numberInArray = [
1, 2,
];
// good
const arr = [[0, 1], [2, 3], [4, 5]];
const objectInArray = [
{
id: 1,
},
{
id: 2,
},
];
const numberInArray = [
1,
2,
];
</code></pre>
</li>
</ul>
<p><strong><a href="#table-of-contents">▲ back to top</a></strong></p>
<h2>Destructuring</h2>
<p><a name="destructuring--object"></a><a name="5.1"></a></p>
<ul>
<li>
<p><a href="#destructuring--object">5.1</a> Use object destructuring when accessing and using multiple properties of an object. eslint: <a href="https://eslint.org/docs/rules/prefer-destructuring" target="_parent" title="prefer-destructuring">prefer-destructuring</a></p>
<blockquote>
<p>Why? Destructuring saves you from creating temporary references for those properties, and from repetitive access of the object. Repeating object access creates more repetitive code, requires more reading, and creates more opportunities for mistakes. Destructuring objects also provides a single site of definition of the object structure that is used in the block, rather than requiring reading the entire block to determine what is used.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;
return `${firstName} ${lastName}`;
}
// good
function getFullName(user) {
const { firstName, lastName } = user;
return `${firstName} ${lastName}`;
}
// best
function getFullName({ firstName, lastName }) {
return `${firstName} ${lastName}`;
}
</code></pre>
</li>
</ul>
<p><a name="destructuring--array"></a><a name="5.2"></a></p>
<ul>
<li>
<p><a href="#destructuring--array">5.2</a> Use array destructuring. eslint: <a href="https://eslint.org/docs/rules/prefer-destructuring" target="_parent" title="prefer-destructuring">prefer-destructuring</a></p>
<pre class="code javascript"><code class="javascript">const arr = [1, 2, 3, 4];
// bad
const first = arr[0];
const second = arr[1];
// good
const [first, second] = arr;
</code></pre>
</li>
</ul>
<p><a name="destructuring--object-over-array"></a><a name="5.3"></a></p>
<ul>
<li>
<p><a href="#destructuring--object-over-array">5.3</a> Use object destructuring for multiple return values, not array destructuring.</p>
<blockquote>
<p>Why? You can add new properties over time or change the order of things without breaking call sites.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
function processInput(input) {
// then a miracle occurs
return [left, right, top, bottom];
}
// the caller needs to think about the order of return data
const [left, __, top] = processInput(input);
// good
function processInput(input) {
// then a miracle occurs
return { left, right, top, bottom };
}
// the caller selects only the data they need
const { left, top } = processInput(input);
</code></pre>
</li>
</ul>
<p><strong><a href="#table-of-contents">▲ back to top</a></strong></p>
<h2>Strings</h2>
<p><a name="strings--quotes"></a><a name="6.1"></a></p>
<ul>
<li>
<p><a href="#strings--quotes">6.1</a> Use single quotes <code>''</code> for strings. eslint: <a href="https://eslint.org/docs/rules/quotes.html" target="_parent" title="quotes">quotes</a></p>
<pre class="code javascript"><code class="javascript">// bad
const name = "Capt. Janeway";
// bad - template literals should contain interpolation or newlines
const name = `Capt. Janeway`;
// good
const name = 'Capt. Janeway';
</code></pre>
</li>
</ul>
<p><a name="strings--line-length"></a><a name="6.2"></a></p>
<ul>
<li>
<p><a href="#strings--line-length">6.2</a> Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation.</p>
<blockquote>
<p>Why? Broken strings are painful to work with and make code less searchable.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
const errorMessage = 'This is a super long error that was thrown because \
of Batman. When you stop to think about how Batman had anything to do \
with this, you would get nowhere \
fast.';
// bad
const errorMessage = 'This is a super long error that was thrown because ' +
'of Batman. When you stop to think about how Batman had anything to do ' +
'with this, you would get nowhere fast.';
// good
const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
</code></pre>
</li>
</ul>
<p><a name="es6-template-literals"></a><a name="6.4"></a></p>
<ul>
<li>
<p><a href="#es6-template-literals">6.3</a> When programmatically building up strings, use template strings instead of concatenation. eslint: <a href="https://eslint.org/docs/rules/prefer-template.html" target="_parent" title="prefer-template">prefer-template</a> <a href="https://eslint.org/docs/rules/template-curly-spacing" target="_parent" title="template-curly-spacing">template-curly-spacing</a></p>
<blockquote>
<p>Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
function sayHi(name) {
return 'How are you, ' + name + '?';
}
// bad
function sayHi(name) {
return ['How are you, ', name, '?'].join();
}
// bad
function sayHi(name) {
return `How are you, ${ name }?`;
}
// good
function sayHi(name) {
return `How are you, ${name}?`;
}
</code></pre>
</li>
</ul>
<p><a name="strings--eval"></a><a name="6.5"></a></p>
<ul>
<li><a href="#strings--eval">6.4</a> Never use <code>eval()</code> on a string, it opens too many vulnerabilities. eslint: <a href="https://eslint.org/docs/rules/no-eval" target="_parent" title="no-eval">no-eval</a></li>
</ul>
<p><a name="strings--escaping"></a></p>
<ul>
<li>
<p><a href="#strings--escaping">6.5</a> Do not unnecessarily escape characters in strings. eslint: <a href="https://eslint.org/docs/rules/no-useless-escape" target="_parent" title="no-useless-escape">no-useless-escape</a></p>
<blockquote>
<p>Why? Backslashes harm readability, thus they should only be present when necessary.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
const foo = '\'this\' \i\s \"quoted\"';
// good
const foo = '\'this\' is "quoted"';
const foo = `my name is '${name}'`;
</code></pre>
</li>
</ul>
<p><strong><a href="#table-of-contents">▲ back to top</a></strong></p>
<h2>Functions</h2>
<p><a name="functions--declarations"></a><a name="7.1"></a></p>
<ul>
<li>
<p><a href="#functions--declarations">7.1</a> Use named function expressions instead of function declarations. eslint: <a href="https://eslint.org/docs/rules/func-style" target="_parent" title="func-style">func-style</a></p>
<blockquote>
<p>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. (<a href="https://github.com/airbnb/javascript/issues/794" target="_parent" title="Discussion">Discussion</a>)</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
function foo() {
// ...
}
// bad
const foo = function () {
// ...
};
// good
// lexical name distinguished from the variable-referenced invocation(s)
const short = function longUniqueMoreDescriptiveLexicalFoo() {
// ...
};
</code></pre>
</li>
</ul>
<p><a name="functions--iife"></a><a name="7.2"></a></p>
<ul>
<li>
<p><a href="#functions--iife">7.2</a> Wrap immediately invoked function expressions in parentheses. eslint: <a href="https://eslint.org/docs/rules/wrap-iife.html" target="_parent" title="wrap-iife">wrap-iife</a></p>
<blockquote>
<p>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.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// immediately-invoked function expression (IIFE)
(function () {
console.log('Welcome to the Internet. Please follow me.');
}());
</code></pre>
</li>
</ul>
<p><a name="functions--in-blocks"></a><a name="7.3"></a></p>
<ul>
<li><a href="#functions--in-blocks">7.3</a> Never declare a function in a non-function block (<code>if</code>, <code>while</code>, 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: <a href="https://eslint.org/docs/rules/no-loop-func.html" target="_parent" title="no-loop-func">no-loop-func</a></li>
</ul>
<p><a name="functions--note-on-blocks"></a><a name="7.4"></a></p>
<ul>
<li>
<p><a href="#functions--note-on-blocks">7.4</a> <strong>Note:</strong> ECMA-262 defines a <code>block</code> as a list of statements. A function declaration is not a statement.</p>
<pre class="code javascript"><code class="javascript">// bad
if (currentUser) {
function test() {
console.log('Nope.');
}
}
// good
let test;
if (currentUser) {
test = () => {
console.log('Yup.');
};
}
</code></pre>
</li>
</ul>
<p><a name="functions--arguments-shadow"></a><a name="7.5"></a></p>
<ul>
<li>
<p><a href="#functions--arguments-shadow">7.5</a> Never name a parameter <code>arguments</code>. This will take precedence over the <code>arguments</code> object that is given to every function scope.</p>
<pre class="code javascript"><code class="javascript">// bad
function foo(name, options, arguments) {
// ...
}
// good
function foo(name, options, args) {
// ...
}
</code></pre>
</li>
</ul>
<p><a name="es6-rest"></a><a name="7.6"></a></p>
<ul>
<li>
<p><a href="#es6-rest">7.6</a> Never use <code>arguments</code>, opt to use rest syntax <code>...</code> instead. eslint: <a href="https://eslint.org/docs/rules/prefer-rest-params" target="_parent" title="prefer-rest-params">prefer-rest-params</a></p>
<blockquote>
<p>Why? <code>...</code> is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like like <code>arguments</code>.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
function concatenateAll() {
const args = Array.prototype.slice.call(arguments);
return args.join('');
}
// good
function concatenateAll(...args) {
return args.join('');
}
</code></pre>
</li>
</ul>
<p><a name="es6-default-parameters"></a><a name="7.7"></a></p>
<ul>
<li>
<p><a href="#es6-default-parameters">7.7</a> Use default parameter syntax rather than mutating function arguments.</p>
<pre class="code javascript"><code class="javascript">// really bad
function handleThings(opts) {
// No! We shouldn’t mutate function arguments.
// Double bad: if opts is falsy it'll be set to an object which may
// be what you want but it can introduce subtle bugs.
opts = opts || {};
// ...
}
// still bad
function handleThings(opts) {
if (opts === void 0) {
opts = {};
}
// ...
}
// good
function handleThings(opts = {}) {
// ...
}
</code></pre>
</li>
</ul>
<p><a name="functions--default-side-effects"></a><a name="7.8"></a></p>
<ul>
<li>
<p><a href="#functions--default-side-effects">7.8</a> Avoid side effects with default parameters.</p>
<blockquote>
<p>Why? They are confusing to reason about.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">var b = 1;
// bad
function count(a = b++) {
console.log(a);
}
count(); // 1
count(); // 2
count(3); // 3
count(); // 3
</code></pre>
</li>
</ul>
<p><a name="functions--defaults-last"></a><a name="7.9"></a></p>
<ul>
<li>
<p><a href="#functions--defaults-last">7.9</a> Always put default parameters last. eslint: <a href="https://eslint.org/docs/rules/default-param-last" target="_parent" title="default-param-last">default-param-last</a></p>
<pre class="code javascript"><code class="javascript">// bad
function handleThings(opts = {}, name) {
// ...
}
// good
function handleThings(name, opts = {}) {
// ...
}
</code></pre>
</li>
</ul>
<p><a name="functions--constructor"></a><a name="7.10"></a></p>
<ul>
<li>
<p><a href="#functions--constructor">7.10</a> Never use the Function constructor to create a new function. eslint: <a href="https://eslint.org/docs/rules/no-new-func" target="_parent" title="no-new-func">no-new-func</a></p>
<blockquote>
<p>Why? Creating a function in this way evaluates a string similarly to <code>eval()</code>, which opens vulnerabilities.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
var add = new Function('a', 'b', 'return a + b');
// still bad
var subtract = Function('a', 'b', 'return a - b');
</code></pre>
</li>
</ul>
<p><a name="functions--signature-spacing"></a><a name="7.11"></a></p>
<ul>
<li>
<p><a href="#functions--signature-spacing">7.11</a> Spacing in a function signature. eslint: <a href="https://eslint.org/docs/rules/space-before-function-paren" target="_parent" title="space-before-function-paren">space-before-function-paren</a> <a href="https://eslint.org/docs/rules/space-before-blocks" target="_parent" title="space-before-blocks">space-before-blocks</a></p>
<blockquote>
<p>Why? Consistency is good, and you shouldn’t have to add or remove a space when adding or removing a name.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
const f = function(){};
const g = function (){};
const h = function() {};
// good
const x = function () {};
const y = function a() {};
</code></pre>
</li>
</ul>
<p><a name="functions--mutate-params"></a><a name="7.12"></a></p>
<ul>
<li>
<p><a href="#functions--mutate-params">7.12</a> Never mutate parameters. eslint: <a href="https://eslint.org/docs/rules/no-param-reassign.html" target="_parent" title="no-param-reassign">no-param-reassign</a></p>
<blockquote>
<p>Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
function f1(obj) {
obj.key = 1;
}
// good
function f2(obj) {
const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;
}
</code></pre>
</li>
</ul>
<p><a name="functions--reassign-params"></a><a name="7.13"></a></p>
<ul>
<li>
<p><a href="#functions--reassign-params">7.13</a> Never reassign parameters. eslint: <a href="https://eslint.org/docs/rules/no-param-reassign.html" target="_parent" title="no-param-reassign">no-param-reassign</a></p>
<blockquote>
<p>Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the <code>arguments</code> object. It can also cause optimization issues, especially in V8.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
function f1(a) {
a = 1;
// ...
}
function f2(a) {
if (!a) { a = 1; }
// ...
}
// good
function f3(a) {
const b = a || 1;
// ...
}
function f4(a = 1) {
// ...
}
</code></pre>
</li>
</ul>
<p><a name="functions--spread-vs-apply"></a><a name="7.14"></a></p>
<ul>
<li>
<p><a href="#functions--spread-vs-apply">7.14</a> Prefer the use of the spread syntax <code>...</code> to call variadic functions. eslint: <a href="https://eslint.org/docs/rules/prefer-spread" target="_parent" title="prefer-spread">prefer-spread</a></p>
<blockquote>
<p>Why? It’s cleaner, you don’t need to supply a context, and you can not easily compose <code>new</code> with <code>apply</code>.</p>
</blockquote>
<pre class="code javascript"><code class="javascript">// bad
const x = [1, 2, 3, 4, 5];
console.log.apply(console, x);
// good
const x = [1, 2, 3, 4, 5];
console.log(...x);