forked from google/styleguide
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jsguide.html
3807 lines (2818 loc) · 147 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>
<p style="position: fixed; left: 0; top: 0; padding: 0.5em; margin: 0; background-color: #fef6e0; text-align: center; width: 100%; font-weight: bold; z-index: 1;">
Please note: This guide is no longer being updated. Google recommends migrating
to TypeScript, and following the <a href="tsguide.html">TypeScript guide</a>.
</p>
<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>
<pre><code class="language-js prettyprint good">/* Best: perfectly clear even without a comment. */
const units = 'μs';
/* Allowed: but unnecessary as μ is a printable character. */
const units = '\u03bcs'; // 'μs'
/* Good: use escapes for non-printable characters with a comment for clarity. */
return '\ufeff' + content; // Prepend a byte order mark.
</code></pre>
<pre><code class="language-js prettyprint bad">/* Poor: the reader has no idea what character this is. */
const units = '\u03bcs';
</code></pre>
<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>All new source files should either be a <code>goog.module</code>
file (a file containing a <code>goog.module</code> call) or an ECMAScript (ES) module (uses
<code>import</code> and <code>export</code> statements).</p>
<p>Files consist of the following, <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, if a <code>goog.module</code> file</li>
<li>ES <code>import</code> statements, if an ES module</li>
<li><code>goog.require</code> and <code>goog.requireType</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 <code>goog.module</code> 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 <code>goog.module</code> 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 in <code>lowerCamelCase</code>.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint good">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>Disallowed:</p>
<pre><code class="language-js prettyprint bad">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-declare-legacy-namespace">3.3.2 <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 good">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-goog-module-exports">3.3.3 <code>goog.module</code> Exports</h4>
<p>Classes, enums, functions, constants, and other symbols are exported using the
<code>exports</code> object. Exported symbols may be defined directly on the <code>exports</code>
object, or else declared locally and exported separately. Symbols are only
exported if they are meant to be used outside the module. Non-exported
module-local symbols are not declared <code>@private</code>. There is no prescribed
ordering for exported and module-local symbols.</p>
<p>Examples:</p>
<pre><code class="language-js prettyprint good">const /** !Array<number> */ exportedArray = [1, 2, 3];
const /** !Array<number> */ moduleLocalArray = [4, 5, 6];
/** @return {number} */
function moduleLocalFunction() {
return moduleLocalArray.length;
}
/** @return {number} */
function exportedFunction() {
return moduleLocalFunction() * 2;
}
exports = {exportedArray, exportedFunction};
</code></pre>
<pre><code class="language-js prettyprint good">/** @const {number} */
exports.CONSTANT_ONE = 1;
/** @const {string} */
exports.CONSTANT_TWO = 'Another constant';
</code></pre>
<p>Do not annotate the <code>exports</code> object as <code>@const</code> as it is already treated as a
constant by the compiler.</p>
<pre><code class="language-js prettyprint bad">/** @const */
exports = {exportedFunction};
</code></pre>
<p>Do not use default exports as they don't translate easily to ES module
semantics.</p>
<pre><code class="language-js prettyprint bad">exports = FancyClass;
</code></pre>
<p><span id="file-es6-modules"></span></p>
<h3 id="file-es-modules">3.4 ES modules</h3>
<p>ES modules are files that use the <code>import</code> and <code>export</code> keywords.</p>
<p><span id="es6-module-imports"></span></p>
<h4 id="es-module-imports">3.4.1 Imports</h4>
<p>Import statements must not be line wrapped and are therefore an exception to the
80-column limit.</p>
<p><span id="es6-import-paths"></span></p>
<h5 id="esm-import-paths">3.4.1.1 Import paths</h5>
<p>ES module files must use the <code>import</code> statement to import other ES module
files. Do not <code>goog.require</code> another ES module.</p>
<pre><code class="language-js prettyprint good">import './sideeffects.js';
import * as goog from '../closure/goog/goog.js';
import * as parent from '../parent.js';
import {name} from './sibling.js';
</code></pre>
<p><span id="es6-import-paths-file-extension"></span></p>
<h6 id="esm-import-paths-file-extension">3.4.1.1.1 File extensions in import paths</h6>
<p>The <code>.js</code> file extension is not optional in import paths and must always be
included.</p>
<pre><code class="language-js prettyprint bad">import '../directory/file';
</code></pre>
<pre><code class="language-js prettyprint good">import '../directory/file.js';
</code></pre>
<h5 id="importing-the-same-file-multiple-times">3.4.1.2 Importing the same file multiple times</h5>
<p>Do not import the same file multiple times. This can make it hard to determine
the aggregate imports of a file.</p>
<pre><code class="language-js prettyprint bad">// Imports have the same path, but since it doesn't align it can be hard to see.
import {short} from './long/path/to/a/file.js';
import {aLongNameThatBreaksAlignment} from './long/path/to/a/file.js';
</code></pre>
<p><span id="naming-es6-imports"></span></p>
<h5 id="naming-esm-imports">3.4.1.3 Naming imports</h5>
<h6 id="naming-module-imports">3.4.1.3.1 Naming module imports</h6>
<p>Module import names (<code>import * as name</code>) are <code>lowerCamelCase</code> names that are
derived from the imported file name.</p>
<pre><code class="language-js prettyprint good">import * as fileOne from '../file-one.js';
import * as fileTwo from '../file_two.js';
import * as fileThree from '../filethree.js';
</code></pre>
<pre><code class="language-js prettyprint good">import * as libString from './lib/string.js';
import * as math from './math/math.js';
import * as vectorMath from './vector/math.js';
</code></pre>
<p>Some libraries might commonly use a namespace import prefix that violates this
naming scheme, but overbearingly common open source use makes the violating
style more readable. The only library that currently falls under this exception
is <a href="https://threejs.org/">threejs</a>, using the <code>THREE</code> prefix.</p>
<h6 id="naming-default-imports">3.4.1.3.2 Naming default imports</h6>
<p>Default import names are derived from the imported file name and follow the
rules in <a href="#naming-rules-by-identifier-type">??</a>.</p>
<pre><code class="language-js prettyprint good">import MyClass from '../my-class.js';
import myFunction from '../my_function.js';
import SOME_CONSTANT from '../someconstant.js';
</code></pre>
<p>Note: In general this should not happen as default exports are banned by this
style guide, see <a href="#named-vs-default-exports">??</a>. Default imports are only used
to import modules that do not conform to this style guide.</p>
<h6 id="naming-named-imports">3.4.1.3.3 Naming named imports</h6>
<p>In general symbols imported via the named import (<code>import {name}</code>) should keep
the same name. Avoid aliasing imports (<code>import {SomeThing as SomeOtherThing}</code>).
Prefer fixing name collisions by using a module import (<code>import *</code>) or renaming
the exports themselves.</p>
<pre><code class="language-js prettyprint good">import * as bigAnimals from './biganimals.js';
import * as domesticatedAnimals from './domesticatedanimals.js';
new bigAnimals.Cat();
new domesticatedAnimals.Cat();
</code></pre>
<p>If renaming a named import is needed then use components of the imported
module's file name or path in the resulting alias.</p>
<pre><code class="language-js prettyprint good">import {Cat as BigCat} from './biganimals.js';
import {Cat as DomesticatedCat} from './domesticatedanimals.js';
new BigCat();
new DomesticatedCat();
</code></pre>
<p><span id="es6-module-exports"></span></p>
<h4 id="es-module-exports">3.4.2 Exports</h4>
<p>Symbols are only exported if they are meant to be used outside the module.
Non-exported module-local symbols are not declared <code>@private</code>. There is no
prescribed ordering for exported and module-local symbols.</p>
<h5 id="named-vs-default-exports">3.4.2.1 Named vs default exports</h5>
<p>Use named exports in all code. You can apply the <code>export</code> keyword to a
declaration, or use the <code>export {name};</code> syntax.</p>
<p>Do not use default exports. Importing modules must give a name to these values,
which can lead to inconsistencies in naming across modules.</p>
<pre><code class="language-js prettyprint bad">// Do not use default exports:
export default class Foo { ... } // BAD!
</code></pre>
<pre><code class="language-js prettyprint good">// Use named exports:
export class Foo { ... }
</code></pre>
<pre><code class="language-js prettyprint good">// Alternate style named exports:
class Foo { ... }
export {Foo};
</code></pre>
<p><span id="es6-exports-mutability"></span></p>
<h5 id="esm-exports-mutability">3.4.2.2 Mutability of exports</h5>
<p>Exported variables must not be mutated outside of module initialization.</p>
<p>There are alternatives if mutation is needed, including exporting a constant
reference to an object that has mutable fields or exporting accessor functions for
mutable data.</p>
<pre><code class="language-js prettyprint bad">// Bad: both foo and mutateFoo are exported and mutated.
export let /** number */ foo = 0;
/**
* Mutates foo.
*/
export function mutateFoo() {
++foo;
}
/**
* @param {function(number): number} newMutateFoo
*/
export function setMutateFoo(newMutateFoo) {
// Exported classes and functions can be mutated!
mutateFoo = () => {
foo = newMutateFoo(foo);
};
}
</code></pre>
<pre><code class="language-js prettyprint good">// Good: Rather than export the mutable variables foo and mutateFoo directly,
// instead make them module scoped and export a getter for foo and a wrapper for
// mutateFooFunc.
let /** number */ foo = 0;
let /** function(number): number */ mutateFooFunc = (foo) => foo + 1;
/** @return {number} */
export function getFoo() {
return foo;
}
export function mutateFoo() {
foo = mutateFooFunc(foo);
}
/** @param {function(number): number} mutateFoo */
export function setMutateFoo(mutateFoo) {
mutateFooFunc = mutateFoo;
}
</code></pre>
<p><span id="es6-module-circular-dependencies"></span></p>
<h5 id="es-module-export-from">3.4.2.3 export from</h5>
<p><code>export from</code> statements must not be line wrapped and are therefore an
exception to the 80-column limit. This applies to both <code>export from</code> flavors.</p>
<pre><code class="language-js prettyprint good">export {specificName} from './other.js';
export * from './another.js';
</code></pre>
<h4 id="es-module-circular-dependencies">3.4.3 Circular Dependencies in ES modules</h4>
<p>Do not create cycles between ES modules, even though the ECMAScript
specification allows this. Note that it is possible to create cycles with both
the <code>import</code> and <code>export</code> statements.</p>
<pre><code class="language-js prettyprint bad">// a.js
import './b.js';
</code></pre>
<pre><code class="language-js prettyprint bad">// b.js
import './a.js';
// `export from` can cause circular dependencies too!
export {x} from './c.js';
</code></pre>
<pre><code class="language-js prettyprint bad">// c.js
import './b.js';
export let x;
</code></pre>
<p><span id="es6-module-closure-interop"></span></p>
<h4 id="es-module-closure-interop">3.4.4 Interoperating with Closure</h4>
<p><span id="es6-module-referencing-goog"></span></p>
<h5 id="es-module-referencing-goog">3.4.4.1 Referencing goog</h5>
<p>To reference the Closure <code>goog</code> namespace, import Closure's <code>goog.js</code>.</p>
<pre><code class="language-js prettyprint good">import * as goog from '../closure/goog/goog.js';
const {compute} = goog.require('a.name');
export const CONSTANT = compute();
</code></pre>
<p><code>goog.js</code> exports only a subset of properties from the global <code>goog</code> that can be
used in ES modules.</p>
<p><span id="goog-require-in-es6-module"></span></p>
<h5 id="goog-require-in-es-module">3.4.4.2 goog.require in ES modules</h5>
<p><code>goog.require</code> in ES modules works as it does in <code>goog.module</code> files. You can
require any Closure namespace symbol (i.e., symbols created by <code>goog.provide</code> or
<code>goog.module</code>) and <code>goog.require</code> will return the value.</p>
<pre><code class="language-js prettyprint good">import * as goog from '../closure/goog/goog.js';
import * as anEsModule from './anEsModule.js';
const GoogPromise = goog.require('goog.Promise');
const myNamespace = goog.require('my.namespace');
</code></pre>
<p><span id="closure-module-id-in-es6-module"></span></p>
<h5 id="closure-module-id-in-es-module">3.4.4.3 Declaring Closure Module IDs in ES modules</h5>
<p><code>goog.declareModuleId</code> can be used within ES modules to declare a
<code>goog.module</code>-like module ID. This means that this module ID can be
<code>goog.require</code>d, <code>goog.module.get</code>d etc. as if it were
a <code>goog.module</code> that did not call <code>goog.module.declareLegacyNamespace</code>. It does
not create the module ID as a globally available JavaScript symbol.</p>
<p>A <code>goog.require</code> (or <code>goog.module.get</code>) for a module ID from
<code>goog.declareModuleId</code> will always return the module object (as if it was
<code>import *</code>'d). As a result, the argument to <code>goog.declareModuleId</code> should always
end with a <code>lowerCamelCaseName</code>.</p>
<p>Note: It is an error to call <code>goog.module.declareLegacyNamespace</code> in an ES
module, it can only be called from <code>goog.module</code> files. There is no direct way
to associate a <q>legacy</q> namespace with an ES module.</p>
<p><code>goog.declareModuleId</code> should only be used to upgrade Closure files to ES
modules in place, where named exports are used.</p>
<pre><code class="language-js prettyprint good">import * as goog from '../closure/goog.js';
goog.declareModuleId('my.esm');
export class Class {};
</code></pre>
<h3 id="file-set-test-only">3.5 <code>goog.setTestOnly</code></h3>
<p>In a <code>goog.module</code> file the <code>goog.module</code> statement and, if present,
<code>goog.module.declareLegacyNamespace()</code> statement may optionally be followed by a
call to <code>goog.setTestOnly()</code>.</p>
<p>In an ES module the <code>import</code> statements may optionally be
followed by a call to <code>goog.setTestOnly()</code>.</p>
<h3 id="file-goog-require">3.6 <code>goog.require</code> and <code>goog.requireType</code> statements</h3>
<p>Imports are done with <code>goog.require</code> and <code>goog.requireType</code> statements. The
names imported by a <code>goog.require</code> statement may be used both in code and in
type annotations, while those imported by a <code>goog.requireType</code> may be used in
type annotations only.</p>
<p>The <code>goog.require</code> and <code>goog.requireType</code> statements form a contiguous block
with no empty lines. This block follows the <code>goog.module</code> declaration separated
<a href="#source-file-structure">by a single empty line</a>. The entire argument to
<code>goog.require</code> or <code>goog.requireType</code> is a namespace defined by a <code>goog.module</code>
in a separate file. <code>goog.require</code> and <code>goog.requireType</code> statements may not
appear anywhere else in the file.</p>
<p>Each <code>goog.require</code> or <code>goog.requireType</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 dependencies in type annotations or code. Fully
qualified namespaces must not be used anywhere, except as an argument to
<code>goog.require</code> or <code>goog.requireType</code>.</p>
<p><strong>Exception</strong>: Types, variables, and functions declared in externs files have to
use their fully qualified name in type annotations and code.</p>
<p>When <code>goog.require</code> is assigned to a single constant alias, it must match the
final dot-separated component of the imported module's namespace.</p>
<p><strong>Exception</strong>: In certain cases, additional components of the namespace can be
used to form a longer alias. The resulting alias must retain the original
identifier's casing such that it still correctly identifies its type. Longer
aliases may be used to disambiguate otherwise identical aliases, or if it
significantly improves readability. In addition, a longer alias must be used to
prevent masking native types such as <code>Element</code>, <code>Event</code>, <code>Error</code>, <code>Map</code>, and
<code>Promise</code> (for a more complete list, see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects">Standard Built-in Objects</a> and
<a href="https://developer.mozilla.org/en-US/docs/Web/API">Web APIs</a> at MDN).</p>
When renaming destructured aliases, a space must follow the colon
as required in <a href="#formatting-horizontal-whitespace">??</a>.</p>
<p>A file should not contain both a <code>goog.require</code> and a <code>goog.requireType</code>
statement for the same namespace. If the imported name is used both in code and
in type annotations, it should be imported by a single <code>goog.require</code> statement.</p>
<p>If a module is imported only for its side effects, the call must be a
<code>goog.require</code> (not a <code>goog.requireType</code>) and assignment may be omitted. 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 require 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: require lines are an exception to the 80-column
limit.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint good">// Standard alias style.
const asserts = goog.require('goog.asserts');
// Namespace-based alias used to disambiguate.
const testingAsserts = goog.require('goog.testing.asserts');
// Standard destructuring into aliases.
const {MyClass} = goog.require('some.package');
const {MyType} = goog.requireType('other.package');
const {clear, clone} = goog.require('goog.array');
const {Rgb} = goog.require('goog.color');
// Namespace-based destructuring into aliases used to disambiguate.
const {MyClass: NsMyClass} = goog.require('other.ns');
const {SomeType: FooSomeType} = goog.requireType('foo.types');
const {clear: objectClear, clone: objectClone} = goog.require('goog.object');
// Namespace-based destructuring into aliases used to prevent masking native type.
const {Element: RendererElement} = goog.require('web.renderer');
// Out of sequence namespace-based aliases used to improve readability.
// Also, require lines longer than 80 columns must not be wrapped.
const {SomeDataStructure: SomeDataStructureModel} = goog.requireType('identical.package.identifiers.models');
const {SomeDataStructure: SomeDataStructureProto} = goog.require('proto.identical.package.identifiers');
// goog.require without an alias in order to trigger side effects.
/** @suppress {extraRequire} Initializes MyFramework. */
goog.require('my.framework.initialization');
</code></pre>
<p>Discouraged:</p>
<pre><code class="language-js prettyprint bad">// Some legacy code uses a "default export" style to export a single class, enum,
// record type, etc. Do not use this pattern in new JS.
// When using a "default export", prefer destructuring into aliases.
const MyClass = goog.require('some.package.MyClass');
const MyType = goog.requireType('some.package.MyType');
</code></pre>
<pre><code class="language-js prettyprint bad">// If necessary to disambiguate, prefer PackageClass over SomeClass as it is
// closer to the format of the module name.
const SomeClass = goog.require('some.package.Class');
</code></pre>
<p>Disallowed:</p>
<pre><code class="language-js prettyprint bad">// Extra terms must come from the namespace.
const MyClassForBizzing = goog.require('some.package.MyClass');
// Alias must include the entire final namespace component.
const MyClass = goog.require('some.package.MyClassForBizzing');
// Alias must not mask native type (should be `const JspbMap` here).
const Map = goog.require('jspb.Map');
// Don't break goog.require lines over 80 columns.
const SomeDataStructure =
goog.require('proto.identical.package.identifiers.SomeDataStructure');
// Alias must be based on the namespace.
const randomName = goog.require('something.else');
// Missing a space after the colon.
const {Foo:FooProto} = goog.require('some.package.proto.Foo');
// goog.requireType without an alias.
goog.requireType('some.package.with.a.Type');
/**
* @param {!some.unimported.Dependency} param All external types used in JSDoc
* annotations must be goog.require'd, unless declared in externs.
*/
function someFunction(param) {
// goog.require lines must be at the top level before any other code.
const alias = goog.require('my.long.name.alias');
// ...
}
</code></pre>
<h3 id="file-implementation">3.7 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>Disallowed:</p>
<pre><code class="language-js prettyprint bad">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 good">if (shortCondition()) foo();
</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="https://blog.codinghorror.com/new-programming-jargon/#3">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 good">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 good">function doNothing() {}
</code></pre>
<p>Disallowed:</p>
<pre><code class="language-js prettyprint bad">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 good">const a = [
0,
1,
2,
];
const b =
[0, 1, 2];
</code></pre>
<pre><code class="language-js prettyprint good">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 good">const a = {
a: 0,
b: 1,
};
const b =
{a: 0, b: 1};
</code></pre>
<pre><code class="language-js prettyprint good">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). For inheritance, the <code>extends</code> keyword
is sufficient unless the superclass is templatized. Subclasses of templatized
types must explicitly specify the template type in an <code>@extends</code> JSDoc
annotation, even if it is just passing along the same template name.</p>
<p>Example:</p>
<pre><code class="language-js prettyprint good">/** @template T */
class Foo {
/** @param {T} x */
constructor(x) {
/** @type {T} */
this.x = x;
}
}
/** @extends {Foo<number>} */
class Bar extends Foo {
constructor() {
super(42);
}
}
exports.Baz = class extends Bar {
/** @return {number} */
method() {
return this.x;
}
};
</code></pre>
<pre><code class="language-js prettyprint bad">/** @extends {Bar} */ // <-- unnecessary @extends
exports.Baz = class extends Bar {
/** @return {number} */
method() {
return this.x;
}
};
</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 good">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 good">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><code>goog.module</code>, <code>goog.require</code> and <code>goog.requireType</code> statements (see
<a href="#file-goog-module">??</a> and <a href="#file-goog-require">??</a>).</li>
<li>ES module <code>import</code> and <code>export from</code> statements (see
<a href="#es-module-imports">??</a> and <a href="#es-module-export-from">??</a>).</li>
<li>Lines where obeying the column limit is not possible or would hinder
discoverability. Examples include:
<ul>
<li>A long URL which should be clickable in source.</li>
<li>A shell command intended to be copied-and-pasted.</li>
<li>A long string literal which may need to be copied or searched for wholly
(e.g., a long file path).</li>
</ul></li>
</ol>
<h3 id="formatting-line-wrapping">4.5 Line-wrapping</h3>
<p><strong>Terminology Note</strong>: <em>Line wrapping</em> is breaking a chunk of code into multiple
lines to obey column limit, where the chunk could otherwise legally fit in a
single line.</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 good">currentEstimate =
calc(currentEstimate + x * currentEstimate) /