forked from google/styleguide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsguide.html
2816 lines (2143 loc) · 111 KB
/
jsguide.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 lang="en">
<head>
<meta charset="utf-8">
<title>Google JavaScript Style Guide</title>
<link rel="stylesheet" href="javaguide.css">
<script src="include/styleguide.js"></script>
<link rel="shortcut icon" href="https://www.google.com/favicon.ico">
<script src="include/jsguide.js"></script>
</head>
<body onload="initStyleGuide();">
<div id="content">
<h1>Google JavaScript Style Guide</h1>
<h2 id="introduction">1 Introduction</h2>
<p>This document serves as the <strong>complete</strong> definition of Google’s coding standards
for source code in the JavaScript programming language. A JavaScript source file
is described as being <em>in Google Style</em> if and only if it adheres to the rules
herein.</p>
<p>Like other programming style guides, the issues covered span not only aesthetic
issues of formatting, but other types of conventions or coding standards as
well. However, this document focuses primarily on the hard-and-fast rules that
we follow universally, and avoids giving advice that isn't clearly enforceable
(whether by human or tool). </p>
<h3 id="terminology-notes">1.1 Terminology notes</h3>
<p>In this document, unless otherwise clarified:</p>
<ol>
<li><p>The term <em>comment</em> always refers to <em>implementation</em> comments. We do not use
the phrase <q>documentation comments</q>, instead using the common term “JSDoc”
for both human-readable text and machine-readable annotations within
<code>/** … */</code>.</p></li>
<li><p>This Style Guide uses <a href="http://tools.ietf.org/html/rfc2119">RFC 2119</a> terminology when using the phrases <em>must</em>,
<em>must not</em>, <em>should</em>, <em>should not</em>, and <em>may</em>. The terms <em>prefer</em> and
<em>avoid</em> correspond to <em>should</em> and <em>should not</em>, respectively. Imperative
and declarative statements are prescriptive and correspond to <em>must</em>.</p></li>
</ol>
<p>Other <q>terminology notes</q> will appear occasionally throughout the document.</p>
<h3 id="guide-notes">1.2 Guide notes</h3>
<p>Example code in this document is <strong>non-normative</strong>. That is, while the examples
are in Google Style, they may not illustrate the <em>only</em> stylish way to represent
the code. Optional formatting choices made in examples must not be enforced as
rules.</p>
<h2 id="source-file-basics">2 Source file basics</h2>
<h3 id="file-name">2.1 File name</h3>
<p>File names must be all lowercase and may include underscores (<code>_</code>) or dashes
(<code>-</code>), but no additional punctuation. Follow the convention that your project
uses. Filenames’ extension must be <code>.js</code>.</p>
<h3 id="file-encoding">2.2 File encoding: UTF-8</h3>
<p>Source files are encoded in <strong>UTF-8</strong>.</p>
<h3 id="special-characters">2.3 Special characters</h3>
<h4 id="whitespace-characters">2.3.1 Whitespace characters</h4>
<p>Aside from the line terminator sequence, the ASCII horizontal space character
(0x20) is the only whitespace character that appears anywhere in a source
file. This implies that</p>
<ol>
<li><p>All other whitespace characters in string literals are escaped, and</p></li>
<li><p>Tab characters are <strong>not</strong> used for indentation.</p></li>
</ol>
<h4 id="special-escape-sequences">2.3.2 Special escape sequences</h4>
<p>For any character that has a special escape sequence (<code>\'</code>, <code>\"</code>, <code>\\</code>, <code>\b</code>,
<code>\f</code>, <code>\n</code>, <code>\r</code>, <code>\t</code>, <code>\v</code>), that sequence is used rather than the
corresponding numeric escape (e.g <code>\x0a</code>, <code>\u000a</code>, or <code>\u{a}</code>). Legacy octal
escapes are never used.</p>
<h4 id="non-ascii-characters">2.3.3 Non-ASCII characters</h4>
<p>For the remaining non-ASCII characters, either the actual Unicode character
(e.g. <code>∞</code>) or the equivalent hex or Unicode escape (e.g. <code>\u221e</code>) is used,
depending only on which makes the code <strong>easier to read and understand</strong>.</p>
<p>Tip: In the Unicode escape case, and occasionally even when actual Unicode
characters are used, an explanatory comment can be very helpful.</p>
<table>
<thead>
<tr>
<th>Example
</th><th>Discussion
</th></tr></thead><tbody>
<tr>
<td><code class="prettyprint lang-js">const units = 'μs';</code>
</td><td>Best: perfectly clear even without a comment.
</td></tr><tr>
<td>
<code class="prettyprint lang-js">const units = '\u03bcs'; // 'μs'
</code>
</td><td>Allowed, but there’s no reason to do this.
</td></tr><tr>
<td>
<code class="prettyprint lang-js">const units = '\u03bcs'; // Greek letter mu, 's'
</code>
</td><td>Allowed, but awkward and prone to mistakes.
</td></tr><tr>
<td><code class="badcode">const units = '\u03bcs';</code>
</td><td>Poor: the reader has no idea what this is.
</td></tr><tr>
<td>
<code class="prettyprint lang-js">return '\ufeff' + content; // byte order mark
</code>
</td><td>
Good: use escapes for non-printable characters, and comment if
necessary.
</td></tr></tbody></table>
<p>Tip: Never make your code less readable simply out of fear that some programs
might not handle non-ASCII characters properly. If that happens, those programs
are <strong>broken</strong> and they must be <strong>fixed</strong>.</p>
<h2 id="source-file-structure">3 Source file structure</h2>
<p>A source file consists of, <strong>in order</strong>:</p>
<ol>
<li>License or copyright information, if present</li>
<li><code>@fileoverview</code> JSDoc, if present</li>
<li><code>goog.module</code> statement</li>
<li><code>goog.require</code> statements</li>
<li>The file’s implementation</li>
</ol>
<p><strong>Exactly one blank line</strong> separates each section that is present, except the
file's implementation, which may be preceded by 1 or 2 blank lines.</p>
<h3 id="file-copyright">3.1 License or copyright information, if present</h3>
<p>If license or copyright information belongs in a file, it belongs here.</p>
<h3 id="file-fileoverview">3.2 <code>@fileoverview</code> JSDoc, if present</h3>
<p>See <a href="#jsdoc-top-file-level-comments">??</a> for formatting rules.</p>
<h3 id="file-goog-module">3.3 <code>goog.module</code> statement</h3>
<p>All files must declare exactly one <code>goog.module</code> name on a single line: lines
containing a <code>goog.module</code> declaration must not be wrapped, and are therefore an
exception to the 80-column limit.</p>
<p>The entire argument to goog.module is what defines a namespace. It is the
package name (an identifier that reflects the fragment of the directory
structure where the code lives) plus, optionally, the main class/enum/interface
that it defines concatenated to the end.</p>
<p>Example</p>
<pre><code class="language-js prettyprint">goog.module('search.urlHistory.UrlHistoryService');
</code></pre>
<h4 id="naming-hierarchy">3.3.1 Hierarchy</h4>
<p>Module namespaces may never be named as a <em>direct</em> child of another module's
namespace.</p>
<p>Illegal:</p>
<pre><code class="language-js prettyprint badcode">goog.module('foo.bar'); // 'foo.bar.qux' would be fine, though
goog.module('foo.bar.baz');
</code></pre>
<p>The directory hierarchy reflects the namespace hierarchy, so that deeper-nested
children are subdirectories of higher-level parent directories. Note that this
implies that owners of “parent” namespace groups are necessarily aware of all
child namespaces, since they exist in the same directory.</p>
<h4 id="file-set-test-only">3.3.2 <code>goog.setTestOnly</code></h4>
<p>The single <code>goog.module</code> statement may optionally be followed by a call to
goog.setTestOnly().</p>
<h4 id="file-declare-legacy-namespace">3.3.3 <code>goog.module.declareLegacyNamespace</code></h4>
<p>The single <code>goog.module</code> statement may optionally be followed by a call to
<code>goog.module.declareLegacyNamespace();</code>. Avoid
<code>goog.module.declareLegacyNamespace()</code> when possible.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint">goog.module('my.test.helpers');
goog.module.declareLegacyNamespace();
goog.setTestOnly();
</code></pre>
<p><code>goog.module.declareLegacyNamespace</code> exists to ease the transition from
traditional object hierarchy-based namespaces but comes with some naming
restrictions. As the child module name must be created after the parent
namespace, this name <strong>must not</strong> be a child or parent of any other
<code>goog.module</code> (for example, <code>goog.module('parent');</code> and
<code>goog.module('parent.child');</code> cannot both exist safely, nor can
<code>goog.module('parent');</code> and <code>goog.module('parent.child.grandchild');</code>).</p>
<h4 id="file-es6-modules">3.3.4 ES6 Modules</h4>
<p>Do not use ES6 modules yet (i.e. the <code>export</code> and <code>import</code> keywords), as their
semantics are not yet finalized. Note that this policy will be revisited once
the semantics are fully-standard.</p>
<h3 id="file-goog-require">3.4 <code>goog.require</code> statements</h3>
<p>Imports are done with <code>goog.require</code> statements, grouped together immediately
following the module declaration. Each <code>goog.require</code> is assigned to a single
constant alias, or else destructured into several constant aliases. These
aliases are the only acceptable way to refer to the <code>require</code>d dependency,
whether in code or in type annotations: the fully qualified name is never used
except as the argument to <code>goog.require</code>. Alias names should match the final
dot-separated component of the imported module name when possible, though
additional components may be included (with appropriate casing such that the
alias' casing still correctly identifies its type) if necessary to
disambiguate, or if it significantly improves readability. <code>goog.require</code>
statements may not appear anywhere else in the file.</p>
<p>If a module is imported only for its side effects, the assignment may be
omitted, but the fully qualified name may not appear anywhere else in the file.
A comment is required to explain why this is needed and suppress a compiler
warning.</p>
<p>The lines are sorted according to the following rules: All requires with a name
on the left hand side come first, sorted alphabetically by those names. Then
destructuring requires, again sorted by the names on the left hand side.
Finally, any <code>goog.require</code> calls that are standalone (generally these are for
modules imported just for their side effects).</p>
<p>Tip: There’s no need to memorize this order and enforce it manually. You can
rely on your IDE to report requires
that are not sorted correctly.</p>
<p>If a long alias or module name would cause a line to exceed the 80-column limit,
it <strong>must not</strong> be wrapped: goog.require lines are an exception to the 80-column
limit.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint">const MyClass = goog.require('some.package.MyClass');
const NsMyClass = goog.require('other.ns.MyClass');
const googAsserts = goog.require('goog.asserts');
const testingAsserts = goog.require('goog.testing.asserts');
const than80columns = goog.require('pretend.this.is.longer.than80columns');
const {clear, forEach, map} = goog.require('goog.array');
/** @suppress {extraRequire} Initializes MyFramework. */
goog.require('my.framework.initialization');
</code></pre>
<p>Illegal:</p>
<pre><code class="language-js badcode prettyprint">const randomName = goog.require('something.else'); // name must match
const {clear, forEach, map} = // don't break lines
goog.require('goog.array');
function someFunction() {
const alias = goog.require('my.long.name.alias'); // must be at top level
// …
}
</code></pre>
<h4 id="file-goog-forward-declare">3.4.1 <code>goog.forwardDeclare</code></h4>
<p><code>goog.forwardDeclare</code> is not needed very often, but is a valuable tool to break
circular dependencies or to reference late loaded code. These statements are
grouped together and immediately follow any <code>goog.require</code> statements. A
<code>goog.forwardDeclare</code> statement must follow the same style rules as a
<code>goog.require</code> statement.</p>
<h3 id="file-implementation">3.5 The file’s implementation</h3>
<p>The actual implementation follows after all dependency information is declared
(separated by at least one blank line).</p>
<p>This may consist of any module-local declarations (constants, variables,
classes, functions, etc), as well as any exported symbols.
</p>
<h2 id="formatting">4 Formatting</h2>
<p><strong>Terminology Note</strong>: <em>block-like construct</em> refers to the body of a class,
function, method, or brace-delimited block of code. Note that, by
<a href="#features-array-literals">??</a> and <a href="#features-object-literals">??</a>, any array or
object literal may optionally be treated as if it were a block-like construct.</p>
<p>Tip: Use <code>clang-format</code>. The JavaScript community has invested effort to make
sure clang-format <q>does the right thing</q> on JavaScript files. <code>clang-format</code> has
integration with several popular
editors.</p>
<h3 id="formatting-braces">4.1 Braces</h3>
<h4 id="formatting-braces-all">4.1.1 Braces are used for all control structures</h4>
<p>Braces are required for all control structures (i.e. <code>if</code>, <code>else</code>, <code>for</code>, <code>do</code>,
<code>while</code>, as well as any others), even if the body contains only a single
statement. The first statement of a non-empty block must begin on its own line.</p>
<p>Illegal:</p>
<pre><code class="language-js badcode prettyprint">if (someVeryLongCondition())
doSomething();
for (let i = 0; i < foo.length; i++) bar(foo[i]);
</code></pre>
<p><strong>Exception</strong>: A simple if statement that can fit entirely on a single line with
no wrapping (and that doesn’t have an else) may be kept on a single line with no
braces when it improves readability. This is the only case in which a control
structure may omit braces and newlines.</p>
<pre><code class="language-js prettyprint">if (shortCondition()) return;
</code></pre>
<h4 id="formatting-nonempty-blocks">4.1.2 Nonempty blocks: K&R style</h4>
<p>Braces follow the Kernighan and Ritchie style (<q><a href="http://www.codinghorror.com/blog/2012/07/new-programming-jargon.html">Egyptian brackets</a></q>) for
<em>nonempty</em> blocks and block-like constructs:</p>
<ul>
<li>No line break before the opening brace.</li>
<li>Line break after the opening brace.</li>
<li>Line break before the closing brace.</li>
<li>Line break after the closing brace <em>if</em> that brace terminates a statement or
the body of a function or class statement, or a class method. Specifically,
there is <em>no</em> line break after the brace if it is followed by <code>else</code>, <code>catch</code>,
<code>while</code>, or a comma, semicolon, or right-parenthesis.</li>
</ul>
<p>Example:</p>
<pre><code class="language-js prettyprint">class InnerClass {
constructor() {}
/** @param {number} foo */
method(foo) {
if (condition(foo)) {
try {
// Note: this might fail.
something();
} catch (err) {
recover();
}
}
}
}
</code></pre>
<h4 id="formatting-empty-blocks">4.1.3 Empty blocks: may be concise</h4>
<p>An empty block or block-like construct <em>may</em> be closed immediately after it is
opened, with no characters, space, or line break in between (i.e. <code>{}</code>),
<strong>unless</strong> it is a part of a <em>multi-block statement</em> (one that directly contains
multiple blocks: <code>if</code>/<code>else</code> or <code>try</code>/<code>catch</code>/<code>finally</code>).</p>
<p>Example:</p>
<pre><code class="language-js prettyprint">function doNothing() {}
</code></pre>
<p>Illegal:</p>
<pre><code class="language-js prettyprint badcode">if (condition) {
// …
} else if (otherCondition) {} else {
// …
}
try {
// …
} catch (e) {}
</code></pre>
<h3 id="formatting-block-indentation">4.2 Block indentation: +2 spaces</h3>
<p>Each time a new block or block-like construct is opened, the indent increases by
two spaces. When the block ends, the indent returns to the previous indent
level. The indent level applies to both code and comments throughout the
block. (See the example in <a href="#formatting-nonempty-blocks">??</a>).</p>
<h4 id="formatting-array-literals">4.2.1 Array literals: optionally <q>block-like</q></h4>
<p>Any array literal may optionally be formatted as if it were a “block-like
construct.” For example, the following are all valid (<strong>not</strong> an exhaustive
list):</p>
<pre><code class="language-js prettyprint columns">const a = [
0,
1,
2,
];
const b =
[0, 1, 2];
</code></pre>
<pre><code class="language-js prettyprint columns">const c = [0, 1, 2];
someMethod(foo, [
0, 1, 2,
], bar);
</code></pre>
<p>Other combinations are allowed, particularly when emphasizing semantic groupings
between elements, but should not be used only to reduce the vertical size of
larger arrays.</p>
<h4 id="formatting-object-literals">4.2.2 Object literals: optionally <q>block-like</q></h4>
<p>Any object literal may optionally be formatted as if it were a “block-like
construct.” The same examples apply as <a href="#formatting-array-literals">??</a>. For
example, the following are all valid (<strong>not</strong> an exhaustive list):</p>
<pre><code class="language-js prettyprint columns">const a = {
a: 0,
b: 1,
};
const b =
{a: 0, b: 1};
</code></pre>
<pre><code class="language-js prettyprint columns">const c = {a: 0, b: 1};
someMethod(foo, {
a: 0, b: 1,
}, bar);
</code></pre>
<h4 id="formatting-class-literals">4.2.3 Class literals</h4>
<p>Class literals (whether declarations or expressions) are indented as blocks. Do
not add semicolons after methods, or after the closing brace of a class
<em>declaration</em> (statements—such as assignments—that contain class <em>expressions</em>
are still terminated with a semicolon). Use the <code>extends</code> keyword, but not the
<code>@extends</code> JSDoc annotation unless the class extends a templatized type.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint columns">class Foo {
constructor() {
/** @type {number} */
this.x = 42;
}
/** @return {number} */
method() {
return this.x;
}
}
Foo.Empty = class {};
</code></pre>
<pre><code class="language-js prettyprint columns">/** @extends {Foo<string>} */
foo.Bar = class extends Foo {
/** @override */
method() {
return super.method() / 2;
}
};
/** @interface */
class Frobnicator {
/** @param {string} message */
frobnicate(message) {}
}
</code></pre>
<h4 id="formatting-function-expressions">4.2.4 Function expressions</h4>
<p>When declaring an anonymous function in the list of arguments for a function
call, the body of the function is indented two spaces more than the preceding
indentation depth.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint">prefix.something.reallyLongFunctionName('whatever', (a1, a2) => {
// Indent the function body +2 relative to indentation depth
// of the 'prefix' statement one line above.
if (a1.equals(a2)) {
someOtherLongFunctionName(a1);
} else {
andNowForSomethingCompletelyDifferent(a2.parrot);
}
});
some.reallyLongFunctionCall(arg1, arg2, arg3)
.thatsWrapped()
.then((result) => {
// Indent the function body +2 relative to the indentation depth
// of the '.then()' call.
if (result) {
result.use();
}
});
</code></pre>
<h4 id="formatting-switch-statements">4.2.5 Switch statements</h4>
<p>As with any other block, the contents of a switch block are indented +2.</p>
<p>After a switch label, a newline appears, and the indentation level is increased
+2, exactly as if a block were being opened. An explicit block may be used if
required by lexical scoping. The following switch label returns to the previous
indentation level, as if a block had been closed.</p>
<p>A blank line is optional between a <code>break</code> and the following case.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint">switch (animal) {
case Animal.BANDERSNATCH:
handleBandersnatch();
break;
case Animal.JABBERWOCK:
handleJabberwock();
break;
default:
throw new Error('Unknown animal');
}
</code></pre>
<h3 id="formatting-statements">4.3 Statements</h3>
<h4 id="formatting-one-statement-perline">4.3.1 One statement per line</h4>
<p>Each statement is followed by a line-break.</p>
<h4 id="formatting-semicolons-are-required">4.3.2 Semicolons are required</h4>
<p>Every statement must be terminated with a semicolon. Relying on automatic
semicolon insertion is forbidden.</p>
<h3 id="formatting-column-limit">4.4 Column limit: 80</h3>
<p>JavaScript code has a column limit of 80 characters. Except as noted below, any
line that would exceed this limit must be line-wrapped, as explained in
<a href="#formatting-line-wrapping">??</a>.</p>
<p><strong>Exceptions:</strong></p>
<ol>
<li>Lines where obeying the column limit is not possible (for example, a long URL
in JSDoc or a shell command intended to be copied-and-pasted).</li>
<li><code>goog.module</code> and <code>goog.require</code> statements (see <a href="#file-goog-module">??</a> and
<a href="#file-goog-require">??</a>).</li>
</ol>
<h3 id="formatting-line-wrapping">4.5 Line-wrapping</h3>
<p><strong>Terminology Note</strong>: <em>Line-wrapping</em> is defined as breaking a single expression
into multiple lines.</p>
<p>There is no comprehensive, deterministic formula showing <em>exactly</em> how to
line-wrap in every situation. Very often there are several valid ways to
line-wrap the same piece of code.</p>
<p>Note: While the typical reason for line-wrapping is to avoid overflowing the
column limit, even code that would in fact fit within the column limit may be
line-wrapped at the author's discretion.</p>
<p>Tip: Extracting a method or local variable may solve the problem without the
need to line-wrap.</p>
<h4 id="formatting-where-to-break">4.5.1 Where to break</h4>
<p>The prime directive of line-wrapping is: prefer to break at a <strong>higher syntactic
level</strong>. </p>
<p>Preferred:</p>
<pre><code class="language-js prettyprint">currentEstimate =
calc(currentEstimate + x * currentEstimate) /
2.0f;
</code></pre>
<p>Discouraged:</p>
<pre><code class="language-js prettyprint badcode">currentEstimate = calc(currentEstimate + x *
currentEstimate) / 2.0f;
</code></pre>
<p>In the preceding example, the syntactic levels from highest to lowest are as
follows: assignment, division, function call, parameters, number constant.</p>
<p>Operators are wrapped as follows:</p>
<ol>
<li>When a line is broken at an operator the break comes after the symbol. (Note
that this is not the same practice used in Google style for Java.)
<ol>
<li>This does not apply to the <q>dot</q> (<code>.</code>), which is not actually an
operator.</li>
</ol></li>
<li>A method or constructor name stays attached to the open parenthesis (<code>(</code>)
that follows it.</li>
<li>A comma (<code>,</code>) stays attached to the token that precedes it.</li>
</ol>
<blockquote>
<p>Note: The primary goal for line wrapping is to have clear code, not
necessarily code that fits in the smallest number of lines.</p>
</blockquote>
<h4 id="formatting-indent">4.5.2 Indent continuation lines at least +4 spaces</h4>
<p>When line-wrapping, each line after the first (each <em>continuation line</em>) is
indented at least +4 from the original line, unless it falls under the rules of
block indentation.</p>
<p>When there are multiple continuation lines, indentation may be varied beyond +4
as appropriate. In general, continuation lines at a deeper syntactic level are
indented by larger multiples of 4, and two lines use the same indentation level
if and only if they begin with syntactically parallel elements.</p>
<p><a href="#formatting-horizontal-alignment">??</a> addresses the discouraged practice of
using a variable number of spaces to align certain tokens with previous lines.</p>
<h3 id="formatting-whitespace">4.6 Whitespace</h3>
<h4 id="formatting-vertical-whitespace">4.6.1 Vertical whitespace</h4>
<p>A single blank line appears:</p>
<ol>
<li>Between consecutive methods in a class or object literal
<ol>
<li>Exception: A blank line between two consecutive properties definitions in
an object literal (with no other code between them) is optional. Such
blank lines are used as needed to create <em>logical groupings</em> of fields.</li>
</ol></li>
<li>Within method bodies, sparingly to create <em>logical groupings</em> of statements.
Blank lines at the start or end of a function body are not allowed.</li>
<li><em>Optionally</em> before the first or after the last method in a class or object
literal (neither encouraged nor discouraged).</li>
<li>As required by other sections of this document (e.g.
<a href="#file-goog-require">??</a>).</li>
</ol>
<p><em>Multiple</em> consecutive blank lines are permitted, but never required (nor
encouraged).</p>
<h4 id="formatting-horizontal-whitespace">4.6.2 Horizontal whitespace</h4>
<p>Use of horizontal whitespace depends on location, and falls into three broad
categories: <em>leading</em> (at the start of a line), <em>trailing</em> (at the end of a
line), and <em>internal</em>. Leading whitespace (i.e., indentation) is addressed
elsewhere. Trailing whitespace is forbidden.</p>
<p>Beyond where required by the language or other style rules, and apart from
literals, comments, and JSDoc, a single internal ASCII space also appears in the
following places <strong>only</strong>.</p>
<ol>
<li>Separating any reserved word (such as <code>if</code>, <code>for</code>, or <code>catch</code>) from an open
parenthesis (<code>(</code>) that follows it on that line.</li>
<li>Separating any reserved word (such as <code>else</code> or <code>catch</code>) from a closing
curly brace (<code>}</code>) that precedes it on that line.</li>
<li>Before any open curly brace (<code>{</code>), with two exceptions:
<ol>
<li>Before an object literal that is the first argument of a function or the
first element in an array literal (e.g. <code>foo({a: [{c: d}]})</code>).</li>
<li>In a template expansion, as it is forbidden by the language
(e.g. <code>abc${1 + 2}def</code>).</li>
</ol></li>
<li>On both sides of any binary or ternary operator.</li>
<li>After a comma (<code>,</code>) or semicolon (<code>;</code>). Note that spaces are <em>never</em> allowed
before these characters.</li>
<li>After the colon (<code>:</code>) in an object literal.</li>
<li>On both sides of the double slash (<code>//</code>) that begins an end-of-line
comment. Here, multiple spaces are allowed, but not required.</li>
<li>After an open-JSDoc comment character and on both sides of close characters
(e.g. for short-form type declarations or casts: <code>this.foo = /** @type
{number} */ (bar);</code> or <code>function(/** string */ foo) {</code>).</li>
</ol>
<h4 id="formatting-horizontal-alignment">4.6.3 Horizontal alignment: discouraged</h4>
<p><strong>Terminology Note</strong>: <em>Horizontal alignment</em> is the practice of adding a
variable number of additional spaces in your code with the goal of making
certain tokens appear directly below certain other tokens on previous lines.</p>
<p>This practice is permitted, but it is <strong>generally discouraged</strong> by Google
Style. It is not even required to <em>maintain</em> horizontal alignment in places
where it was already used.</p>
<p>Here is an example without alignment, followed by one with alignment. Both are
allowed, but the latter is discouraged:</p>
<pre><code class="language-js prettyprint">{
tiny: 42, // this is great
longer: 435, // this too
};
{
tiny: 42, // permitted, but future edits
longer: 435, // may leave it unaligned
};
</code></pre>
<p>Tip: Alignment can aid readability, but it creates problems for future
maintenance. Consider a future change that needs to touch just one line. This
change may leave the formerly-pleasing formatting mangled, and that is
allowed. More often it prompts the coder (perhaps you) to adjust whitespace on
nearby lines as well, possibly triggering a cascading series of
reformattings. That one-line change now has a <q>blast radius.</q> This can at worst
result in pointless busywork, but at best it still corrupts version history
information, slows down reviewers and exacerbates merge conflicts.</p>
<h4 id="formatting-function-arguments">4.6.4 Function arguments</h4>
<p>Prefer to put all function arguments on the same line as the function name. If doing so would exceed the 80-column limit, the arguments must be line-wrapped in a readable way. To save space, you may wrap as close to 80 as possible, or put each argument on its own line to enhance readability. Indentation should be four spaces. Aligning to the parenthesis is allowed, but discouraged. Below are the most common patterns for argument wrapping:</p>
<pre><code class="language-js prettyprint">// Arguments start on a new line, indented four spaces. Preferred when the
// arguments don't fit on the same line with the function name (or the keyword
// "function") but fit entirely on the second line. Works with very long
// function names, survives renaming without reindenting, low on space.
doSomething(
descriptiveArgumentOne, descriptiveArgumentTwo, descriptiveArgumentThree) {
// …
}
// If the argument list is longer, wrap at 80. Uses less vertical space,
// but violates the rectangle rule and is thus not recommended.
doSomething(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,
tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {
// …
}
// Four-space, one argument per line. Works with long function names,
// survives renaming, and emphasizes each argument.
doSomething(
veryDescriptiveArgumentNumberOne,
veryDescriptiveArgumentTwo,
tableModelEventHandlerProxy,
artichokeDescriptorAdapterIterator) {
// …
}
</code></pre>
<h3 id="formatting-grouping-parentheses">4.7 Grouping parentheses: recommended</h3>
<p>Optional grouping parentheses are omitted only when the author and reviewer
agree that there is no reasonable chance that the code will be misinterpreted
without them, nor would they have made the code easier to read. It is <em>not</em>
reasonable to assume that every reader has the entire operator precedence table
memorized.</p>
<p>Do not use unnecessary parentheses around the entire expression following
<code>delete</code>, <code>typeof</code>, <code>void</code>, <code>return</code>, <code>throw</code>, <code>case</code>, <code>in</code>, <code>of</code>, or <code>yield</code>.</p>
<p>Parentheses are required for type casts: <code>/** @type {!Foo} */ (foo)</code>.</p>
<h3 id="formatting-comments">4.8 Comments</h3>
<p>This section addresses <em>implementation comments</em>. JSDoc is addressed separately
in <a href="#jsdoc">??</a>.</p>
<h4 id="formatting-block-comment-style">4.8.1 Block comment style</h4>
<p>Block comments are indented at the same level as the surrounding code. They may
be in <code>/* … */</code> or <code>//</code>-style. For multi-line <code>/* … */</code> comments, subsequent
lines must start with * aligned with the <code>*</code> on the previous line, to make
comments obvious with no extra context. “Parameter name” comments should appear
after values whenever the value and method name do not sufficiently convey the
meaning.</p>
<pre><code class="language-js prettyprint">/*
* This is
* okay.
*/
// And so
// is this.
/* This is fine, too. */
someFunction(obviousParam, true /* shouldRender */, 'hello' /* name */);
</code></pre>
<p>Comments are not enclosed in boxes drawn with asterisks or other characters.</p>
<p>Do not use JSDoc (<code>/** … */</code>) for any of the above implementation comments.</p>
<h2 id="language-features">5 Language features</h2>
<p>JavaScript includes many dubious (and even dangerous) features. This section
delineates which features may or may not be used, and any additional constraints
on their use.</p>
<h3 id="features-local-variable-declarations">5.1 Local variable declarations</h3>
<h4 id="features-use-const-and-let">5.1.1 Use <code>const</code> and <code>let</code></h4>
<p>Declare all local variables with either <code>const</code> or <code>let</code>. Use const by default,
unless a variable needs to be reassigned. The <code class="badcode">var</code>
keyword must not be used.</p>
<h4 id="features-one-variable-per-declaration">5.1.2 One variable per declaration</h4>
<p>Every local variable declaration declares only one variable: declarations such
as <code class="badcode">let a = 1, b = 2;</code> are not used.</p>
<h4 id="features-declared-when-needed">5.1.3 Declared when needed, initialized as soon as possible</h4>
<p>Local variables are <strong>not</strong> habitually declared at the start of their containing
block or block-like construct. Instead, local variables are declared close to
the point they are first used (within reason), to minimize their scope.</p>
<h4 id="features-declare-types-as-needed">5.1.4 Declare types as needed</h4>
<p>JSDoc type annotations may be added either on the line above the declaration, or
else inline before the variable name.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint">const /** !Array<number> */ data = [];
/** @type {!Array<number>} */
const data = [];
</code></pre>
<p>Tip: There are many cases where the compiler can infer a templatized type but
not its parameters. This is particularly the case when the initializing literal
or constructor call does not include any values of the template parameter type
(e.g., empty arrays, objects, <code>Map</code>s, or <code>Set</code>s), or if the variable is modified
in a closure. Local variable type annotations are particularly helpful in these
cases since otherwise the compiler will infer the template parameter as unknown.</p>
<h3 id="features-array-literals">5.2 Array literals</h3>
<h4 id="features-arrays-trailing-comma">5.2.1 Use trailing commas</h4>
<p>Include a trailing comma whenever there is a line break between the final
element and the closing bracket.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint">const values = [
'first value',
'second value',
];
</code></pre>
<h4 id="features-arrays-ctor">5.2.2 Do not use the variadic <code>Array</code> constructor</h4>
<p>The constructor is error-prone if arguments are added or removed. Use a literal
instead.</p>
<p>Illegal:</p>
<pre><code class="language-js prettyprint badcode">const a1 = new Array(x1, x2, x3);
const a2 = new Array(x1, x2);
const a3 = new Array(x1);
const a4 = new Array();
</code></pre>
<p>This works as expected except for the third case: if <code>x1</code> is a whole number then
<code>a3</code> is an array of size <code>x1</code> where all elements are <code>undefined</code>. If <code>x1</code> is any
other number, then an exception will be thrown, and if it is anything else then
it will be a single-element array.</p>
<p>Instead, write</p>
<pre><code class="language-js prettyprint">const a1 = [x1, x2, x3];
const a2 = [x1, x2];
const a3 = [x1];
const a4 = [];
</code></pre>
<p>Explicitly allocating an array of a given length using <code>new Array(length)</code> is
allowed when appropriate.</p>
<h4 id="features-arrays-non-numeric-properties">5.2.3 Non-numeric properties</h4>
<p>Do not define or use non-numeric properties on an array (other than
<code>length</code>). Use a <code>Map</code> (or <code>Object</code>) instead.</p>
<h4 id="features-arrays-destructuring">5.2.4 Destructuring</h4>
<p>Array literals may be used on the left-hand side of an assignment to perform
destructuring (such as when unpacking multiple values from a single array or
iterable). A final <q>rest</q> element may be included (with no space between the
<code>...</code> and the variable name). Elements should be omitted if they are unused.</p>
<pre><code class="language-js prettyprint">const [a, b, c, ...rest] = generateResults();
let [, b,, d] = someArray;
</code></pre>
<p>Destructuring may also be used for function parameters (note that a parameter
name is required but ignored). Always specify <code>[]</code> as the default value if a
destructured array parameter is optional, and provide default values on the left
hand side:</p>
<pre><code class="language-js prettyprint">/** @param {!Array<number>=} param1 */
function optionalDestructuring([a = 4, b = 2] = []) { … };
</code></pre>
<p>Illegal:</p>
<pre><code class="language-js prettyprint badcode">function badDestructuring([a, b] = [4, 2]) { … };
</code></pre>
<p>Tip: For (un)packing multiple values into a function’s parameter or return,
prefer object destructuring to array destructuring when possible, as it allows
naming the individual elements and specifying a different type for each.*</p>
<h4 id="features-arrays-spread-operator">5.2.5 Spread operator</h4>
<p>Array literals may include the spread operator (<code>...</code>) to flatten elements out
of one or more other iterables. The spread operator should be used instead of
more awkward constructs with <code>Array.prototype</code>. There is no space after the
<code>...</code>.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint">[...foo] // preferred over Array.prototype.slice.call(foo)
[...foo, ...bar] // preferred over foo.concat(bar)
</code></pre>
<h3 id="features-object-literals">5.3 Object literals</h3>
<h4 id="features-objects-use-trailing-comma">5.3.1 Use trailing commas</h4>
<p>Include a trailing comma whenever there is a line break between the final
property and the closing brace.</p>
<h4 id="features-objects-ctor">5.3.2 Do not use the <code>Object</code> constructor</h4>
<p>While <code>Object</code> does not have the same problems as <code>Array</code>, it is still
disallowed for consistency. Use an object literal (<code>{}</code> or <code>{a: 0, b: 1, c: 2}</code>)
instead.</p>
<h4 id="features-objects-mixing-keys">5.3.3 Do not mix quoted and unquoted keys</h4>
<p>Object literals may represent either <em>structs</em> (with unquoted keys and/or
symbols) or <em>dicts</em> (with quoted and/or computed keys). Do not mix these key
types in a single object literal.</p>
<p>Illegal:</p>
<pre><code class="language-js prettyprint badcode">{
a: 42, // struct-style unquoted key
'b': 43, // dict-style quoted key
}
</code></pre>
<h4 id="features-objects-computed-property-names">5.3.4 Computed property names</h4>
<p>Computed property names (e.g., <code>{['key' + foo()]: 42}</code>) are allowed, and are
considered dict-style (quoted) keys (i.e., must not be mixed with non-quoted
keys) unless the computed property is a symbol (e.g., <code>[Symbol.iterator]</code>).
Enum values may also be used for computed keys, but should not be mixed with
non-enum keys in the same literal.</p>
<h4 id="features-objects-method-shorthand">5.3.5 Method shorthand</h4>
<p>Methods can be defined on object literals using the method shorthand (<code>{method()
{… }}</code>) in place of a colon immediately followed by a <code>function</code> or arrow
function literal.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint">return {
stuff: 'candy',
method() {
return this.stuff; // Returns 'candy'
},
};
</code></pre>
<p>Note that <code>this</code> in a method shorthand or <code>function</code> refers to the object
literal itself whereas <code>this</code> in an arrow function refers to the scope outside
the object literal.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint">class {
getObjectLiteral() {
this.stuff = 'fruit';
return {