readability-cli 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
guides/jsguide.md ADDED
@@ -0,0 +1,3775 @@
1
+ Google JavaScript Style Guide
2
+
3
+
4
+
5
+ # Google JavaScript Style Guide
6
+
7
+ Please note: This guide is no longer being updated. Google recommends migrating
8
+ to TypeScript, and following the [TypeScript guide](tsguide.html).
9
+
10
+ ## 1 Introduction
11
+
12
+ This document serves as the **complete** definition of Google’s coding standards
13
+ for source code in the JavaScript programming language. A JavaScript source file
14
+ is described as being *in Google Style* if and only if it adheres to the rules
15
+ herein.
16
+
17
+ Like other programming style guides, the issues covered span not only aesthetic
18
+ issues of formatting, but other types of conventions or coding standards as
19
+ well. However, this document focuses primarily on the hard-and-fast rules that
20
+ we follow universally, and avoids giving advice that isn't clearly enforceable
21
+ (whether by human or tool).
22
+
23
+ ### 1.1 Terminology notes
24
+
25
+ In this document, unless otherwise clarified:
26
+
27
+ 1. The term *comment* always refers to *implementation* comments. We do not use
28
+ the phrase "documentation comments", instead using the common term “JSDoc”
29
+ for both human-readable text and machine-readable annotations within `/** …
30
+ */`.
31
+ 2. This Style Guide uses [RFC 2119](http://tools.ietf.org/html/rfc2119) terminology when using the phrases *must*,
32
+ *must not*, *should*, *should not*, and *may*. The terms *prefer* and
33
+ *avoid* correspond to *should* and *should not*, respectively. Imperative
34
+ and declarative statements are prescriptive and correspond to *must*.
35
+
36
+ Other "terminology notes" will appear occasionally throughout the document.
37
+
38
+ ### 1.2 Guide notes
39
+
40
+ Example code in this document is **non-normative**. That is, while the examples
41
+ are in Google Style, they may not illustrate the *only* stylish way to represent
42
+ the code. Optional formatting choices made in examples must not be enforced as
43
+ rules.
44
+
45
+ ## 2 Source file basics
46
+
47
+ ### 2.1 File name
48
+
49
+ File names must be all lowercase and may include underscores (`_`) or dashes
50
+ (`-`), but no additional punctuation. Follow the convention that your project
51
+ uses. Filenames’ extension must be `.js`.
52
+
53
+ ### 2.2 File encoding: UTF-8
54
+
55
+ Source files are encoded in **UTF-8**.
56
+
57
+ ### 2.3 Special characters
58
+
59
+ #### 2.3.1 Whitespace characters
60
+
61
+ Aside from the line terminator sequence, the ASCII horizontal space character
62
+ (0x20) is the only whitespace character that appears anywhere in a source file.
63
+ This implies that
64
+
65
+ 1. All other whitespace characters in string literals are escaped, and
66
+ 2. Tab characters are **not** used for indentation.
67
+
68
+ #### 2.3.2 Special escape sequences
69
+
70
+ For any character that has a special escape sequence (`\'`, `\"`, `\\`, `\b`,
71
+ `\f`, `\n`, `\r`, `\t`, `\v`), that sequence is used rather than the
72
+ corresponding numeric escape (e.g `\x0a`, `\u000a`, or `\u{a}`). Legacy octal
73
+ escapes are never used.
74
+
75
+ #### 2.3.3 Non-ASCII characters
76
+
77
+ For the remaining non-ASCII characters, either the actual Unicode character
78
+ (e.g. `∞`) or the equivalent hex or Unicode escape (e.g. `\u221e`) is used,
79
+ depending only on which makes the code **easier to read and understand**.
80
+
81
+ Tip: In the Unicode escape case, and occasionally even when actual Unicode
82
+ characters are used, an explanatory comment can be very helpful.
83
+
84
+ ```
85
+ /* Best: perfectly clear even without a comment. */
86
+ const units = 'μs';
87
+
88
+ /* Allowed: but unnecessary as μ is a printable character. */
89
+ const units = '\u03bcs'; // 'μs'
90
+
91
+ /* Good: use escapes for non-printable characters with a comment for clarity. */
92
+ return '\ufeff' + content; // Prepend a byte order mark.
93
+ ```
94
+
95
+ ```
96
+ /* Poor: the reader has no idea what character this is. */
97
+ const units = '\u03bcs';
98
+ ```
99
+
100
+ Tip: Never make your code less readable simply out of fear that some programs
101
+ might not handle non-ASCII characters properly. If that happens, those programs
102
+ are **broken** and they must be **fixed**.
103
+
104
+ ## 3 Source file structure
105
+
106
+ All new source files should either be a `goog.module`
107
+ file (a file containing a `goog.module` call) or an ECMAScript (ES) module (uses
108
+ `import` and `export` statements).
109
+
110
+ Files consist of the following, **in order**:
111
+
112
+ 1. License or copyright information, if present
113
+ 2. `@fileoverview` JSDoc, if present
114
+ 3. `goog.module` statement, if a `goog.module` file
115
+ 4. ES `import` statements, if an ES module
116
+ 5. `goog.require` and `goog.requireType` statements
117
+ 6. The file’s implementation
118
+
119
+ **Exactly one blank line** separates each section that is present, except the
120
+ file's implementation, which may be preceded by 1 or 2 blank lines.
121
+
122
+ ### 3.1 License or copyright information, if present
123
+
124
+ If license or copyright information belongs in a file, it belongs here.
125
+
126
+ ### 3.2 `@fileoverview` JSDoc, if present
127
+
128
+ See [??](#jsdoc-top-file-level-comments) for formatting rules.
129
+
130
+ ### 3.3 `goog.module` statement
131
+
132
+ All `goog.module` files must declare exactly one `goog.module` name on a single
133
+ line: lines containing a `goog.module` declaration must not be wrapped, and are
134
+ therefore an exception to the 80-column limit.
135
+
136
+ The entire argument to `goog.module` is what defines a namespace. It is the
137
+ package name (an identifier that reflects the fragment of the directory
138
+ structure where the code lives) plus, optionally, the main class/enum/interface
139
+ that it defines concatenated to the end in `lowerCamelCase`.
140
+
141
+ Example:
142
+
143
+ ```
144
+ goog.module('search.urlHistory.urlHistoryService');
145
+ ```
146
+
147
+ #### 3.3.1 Hierarchy
148
+
149
+ Module namespaces may never be named as a *direct* child of another module's
150
+ namespace.
151
+
152
+ Disallowed:
153
+
154
+ ```
155
+ goog.module('foo.bar'); // 'foo.bar.qux' would be fine, though
156
+ goog.module('foo.bar.baz');
157
+ ```
158
+
159
+ The directory hierarchy reflects the namespace hierarchy, so that deeper-nested
160
+ children are subdirectories of higher-level parent directories. Note that this
161
+ implies that owners of “parent” namespace groups are necessarily aware of all
162
+ child namespaces, since they exist in the same directory.
163
+
164
+ #### 3.3.2 `goog.module.declareLegacyNamespace`
165
+
166
+ The single `goog.module` statement may optionally be followed by a call to
167
+ `goog.module.declareLegacyNamespace();`. Avoid
168
+ `goog.module.declareLegacyNamespace()` when possible.
169
+
170
+ Example:
171
+
172
+ ```
173
+ goog.module('my.test.helpers');
174
+ goog.module.declareLegacyNamespace();
175
+ goog.setTestOnly();
176
+ ```
177
+
178
+ `goog.module.declareLegacyNamespace` exists to ease the transition from
179
+ traditional object hierarchy-based namespaces but comes with some naming
180
+ restrictions. As the child module name must be created after the parent
181
+ namespace, this name **must not** be a child or parent of any other
182
+ `goog.module` (for example, `goog.module('parent');` and
183
+ `goog.module('parent.child');` cannot both exist safely, nor can
184
+ `goog.module('parent');` and `goog.module('parent.child.grandchild');`).
185
+
186
+ #### 3.3.3 `goog.module` Exports
187
+
188
+ Classes, enums, functions, constants, and other symbols are exported using the
189
+ `exports` object. Exported symbols may be defined directly on the `exports`
190
+ object, or else declared locally and exported separately. Symbols are only
191
+ exported if they are meant to be used outside the module. Non-exported
192
+ module-local symbols are not declared `@private`. There is no prescribed
193
+ ordering for exported and module-local symbols.
194
+
195
+ Examples:
196
+
197
+ ```
198
+ const /** !Array<number> */ exportedArray = [1, 2, 3];
199
+
200
+ const /** !Array<number> */ moduleLocalArray = [4, 5, 6];
201
+
202
+ /** @return {number} */
203
+ function moduleLocalFunction() {
204
+ return moduleLocalArray.length;
205
+ }
206
+
207
+ /** @return {number} */
208
+ function exportedFunction() {
209
+ return moduleLocalFunction() * 2;
210
+ }
211
+
212
+ exports = {exportedArray, exportedFunction};
213
+ ```
214
+
215
+ ```
216
+ /** @const {number} */
217
+ exports.CONSTANT_ONE = 1;
218
+
219
+ /** @const {string} */
220
+ exports.CONSTANT_TWO = 'Another constant';
221
+ ```
222
+
223
+ Do not annotate the `exports` object as `@const` as it is already treated as a
224
+ constant by the compiler.
225
+
226
+ ```
227
+ /** @const */
228
+ exports = {exportedFunction};
229
+ ```
230
+
231
+ Do not use default exports as they don't translate easily to ES module
232
+ semantics.
233
+
234
+ ```
235
+ exports = FancyClass;
236
+ ```
237
+
238
+ ### 3.4 ES modules
239
+
240
+ ES modules are files that use the `import` and `export` keywords.
241
+
242
+ #### 3.4.1 Imports
243
+
244
+ Import statements must not be line wrapped and are therefore an exception to the
245
+ 80-column limit.
246
+
247
+ ##### 3.4.1.1 Import paths
248
+
249
+ ES module files must use the `import` statement to import other ES module
250
+ files. Do not `goog.require` another ES module.
251
+
252
+ ```
253
+ import './sideeffects.js';
254
+
255
+ import * as goog from '../closure/goog/goog.js';
256
+ import * as parent from '../parent.js';
257
+
258
+ import {name} from './sibling.js';
259
+ ```
260
+
261
+ ###### 3.4.1.1.1 File extensions in import paths
262
+
263
+ The `.js` file extension is not optional in import paths and must always be
264
+ included.
265
+
266
+ ```
267
+ import '../directory/file';
268
+ ```
269
+
270
+ ```
271
+ import '../directory/file.js';
272
+ ```
273
+
274
+ ##### 3.4.1.2 Importing the same file multiple times
275
+
276
+ Do not import the same file multiple times. This can make it hard to determine
277
+ the aggregate imports of a file.
278
+
279
+ ```
280
+ // Imports have the same path, but since it doesn't align it can be hard to see.
281
+ import {short} from './long/path/to/a/file.js';
282
+ import {aLongNameThatBreaksAlignment} from './long/path/to/a/file.js';
283
+ ```
284
+
285
+ ##### 3.4.1.3 Naming imports
286
+
287
+ ###### 3.4.1.3.1 Naming module imports
288
+
289
+ Module import names (`import * as name`) are `lowerCamelCase` names that are
290
+ derived from the imported file name.
291
+
292
+ ```
293
+ import * as fileOne from '../file-one.js';
294
+ import * as fileTwo from '../file_two.js';
295
+ import * as fileThree from '../filethree.js';
296
+ ```
297
+
298
+ ```
299
+ import * as libString from './lib/string.js';
300
+ import * as math from './math/math.js';
301
+ import * as vectorMath from './vector/math.js';
302
+ ```
303
+
304
+ Some libraries might commonly use a namespace import prefix that violates this
305
+ naming scheme, but overbearingly common open source use makes the violating
306
+ style more readable. The only library that currently falls under this exception
307
+ is [threejs](https://threejs.org/), using the `THREE` prefix.
308
+
309
+ ###### 3.4.1.3.2 Naming default imports
310
+
311
+ Default import names are derived from the imported file name and follow the
312
+ rules in [??](#naming-rules-by-identifier-type).
313
+
314
+ ```
315
+ import MyClass from '../my-class.js';
316
+ import myFunction from '../my_function.js';
317
+ import SOME_CONSTANT from '../someconstant.js';
318
+ ```
319
+
320
+ Note: In general this should not happen as default exports are banned by this
321
+ style guide, see [??](#named-vs-default-exports). Default imports are only used
322
+ to import modules that do not conform to this style guide.
323
+
324
+ ###### 3.4.1.3.3 Naming named imports
325
+
326
+ In general symbols imported via the named import (`import {name}`) should keep
327
+ the same name. Avoid aliasing imports (`import {SomeThing as SomeOtherThing}`).
328
+ Prefer fixing name collisions by using a module import (`import *`) or renaming
329
+ the exports themselves.
330
+
331
+ ```
332
+ import * as bigAnimals from './biganimals.js';
333
+ import * as domesticatedAnimals from './domesticatedanimals.js';
334
+
335
+ new bigAnimals.Cat();
336
+ new domesticatedAnimals.Cat();
337
+ ```
338
+
339
+ If renaming a named import is needed then use components of the imported
340
+ module's file name or path in the resulting alias.
341
+
342
+ ```
343
+ import {Cat as BigCat} from './biganimals.js';
344
+ import {Cat as DomesticatedCat} from './domesticatedanimals.js';
345
+
346
+ new BigCat();
347
+ new DomesticatedCat();
348
+ ```
349
+
350
+ #### 3.4.2 Exports
351
+
352
+ Symbols are only exported if they are meant to be used outside the module.
353
+ Non-exported module-local symbols are not declared `@private`. There is no
354
+ prescribed ordering for exported and module-local symbols.
355
+
356
+ ##### 3.4.2.1 Named vs default exports
357
+
358
+ Use named exports in all code. You can apply the `export` keyword to a
359
+ declaration, or use the `export {name};` syntax.
360
+
361
+ Do not use default exports. Importing modules must give a name to these values,
362
+ which can lead to inconsistencies in naming across modules.
363
+
364
+ ```
365
+ // Do not use default exports:
366
+ export default class Foo { ... } // BAD!
367
+ ```
368
+
369
+ ```
370
+ // Use named exports:
371
+ export class Foo { ... }
372
+ ```
373
+
374
+ ```
375
+ // Alternate style named exports:
376
+ class Foo { ... }
377
+
378
+ export {Foo};
379
+ ```
380
+
381
+ ##### 3.4.2.2 Mutability of exports
382
+
383
+ Exported variables must not be mutated outside of module initialization.
384
+
385
+ There are alternatives if mutation is needed, including exporting a constant
386
+ reference to an object that has mutable fields or exporting accessor functions for
387
+ mutable data.
388
+
389
+ ```
390
+ // Bad: both foo and mutateFoo are exported and mutated.
391
+ export let /** number */ foo = 0;
392
+
393
+ /**
394
+ * Mutates foo.
395
+ */
396
+ export function mutateFoo() {
397
+ ++foo;
398
+ }
399
+
400
+ /**
401
+ * @param {function(number): number} newMutateFoo
402
+ */
403
+ export function setMutateFoo(newMutateFoo) {
404
+ // Exported classes and functions can be mutated!
405
+ mutateFoo = () => {
406
+ foo = newMutateFoo(foo);
407
+ };
408
+ }
409
+ ```
410
+
411
+ ```
412
+ // Good: Rather than export the mutable variables foo and mutateFoo directly,
413
+ // instead make them module scoped and export a getter for foo and a wrapper for
414
+ // mutateFooFunc.
415
+ let /** number */ foo = 0;
416
+ let /** function(number): number */ mutateFooFunc = (foo) => foo + 1;
417
+
418
+ /** @return {number} */
419
+ export function getFoo() {
420
+ return foo;
421
+ }
422
+
423
+ export function mutateFoo() {
424
+ foo = mutateFooFunc(foo);
425
+ }
426
+
427
+ /** @param {function(number): number} mutateFoo */
428
+ export function setMutateFoo(mutateFoo) {
429
+ mutateFooFunc = mutateFoo;
430
+ }
431
+ ```
432
+
433
+ ##### 3.4.2.3 export from
434
+
435
+ `export from` statements must not be line wrapped and are therefore an
436
+ exception to the 80-column limit. This applies to both `export from` flavors.
437
+
438
+ ```
439
+ export {specificName} from './other.js';
440
+ export * from './another.js';
441
+ ```
442
+
443
+ #### 3.4.3 Circular Dependencies in ES modules
444
+
445
+ Do not create cycles between ES modules, even though the ECMAScript
446
+ specification allows this. Note that it is possible to create cycles with both
447
+ the `import` and `export` statements.
448
+
449
+ ```
450
+ // a.js
451
+ import './b.js';
452
+ ```
453
+
454
+ ```
455
+ // b.js
456
+ import './a.js';
457
+
458
+ // `export from` can cause circular dependencies too!
459
+ export {x} from './c.js';
460
+ ```
461
+
462
+ ```
463
+ // c.js
464
+ import './b.js';
465
+
466
+ export let x;
467
+ ```
468
+
469
+ #### 3.4.4 Interoperating with Closure
470
+
471
+ ##### 3.4.4.1 Referencing goog
472
+
473
+ To reference the Closure `goog` namespace, import Closure's `goog.js`.
474
+
475
+ ```
476
+ import * as goog from '../closure/goog/goog.js';
477
+
478
+ const {compute} = goog.require('a.name');
479
+
480
+ export const CONSTANT = compute();
481
+ ```
482
+
483
+ `goog.js` exports only a subset of properties from the global `goog` that can be
484
+ used in ES modules.
485
+
486
+ ##### 3.4.4.2 goog.require in ES modules
487
+
488
+ `goog.require` in ES modules works as it does in `goog.module` files. You can
489
+ require any Closure namespace symbol (i.e., symbols created by `goog.provide` or
490
+ `goog.module`) and `goog.require` will return the value.
491
+
492
+ ```
493
+ import * as goog from '../closure/goog/goog.js';
494
+ import * as anEsModule from './anEsModule.js';
495
+
496
+ const GoogPromise = goog.require('goog.Promise');
497
+ const myNamespace = goog.require('my.namespace');
498
+ ```
499
+
500
+ ##### 3.4.4.3 Declaring Closure Module IDs in ES modules
501
+
502
+ `goog.declareModuleId` can be used within ES modules to declare a
503
+ `goog.module`-like module ID. This means that this module ID can be
504
+ `goog.require`d, `goog.module.get`d etc. as if it were
505
+ a `goog.module` that did not call `goog.module.declareLegacyNamespace`. It does
506
+ not create the module ID as a globally available JavaScript symbol.
507
+
508
+ A `goog.require` (or `goog.module.get`) for a module ID from
509
+ `goog.declareModuleId` will always return the module object (as if it was
510
+ `import *`'d). As a result, the argument to `goog.declareModuleId` should always
511
+ end with a `lowerCamelCaseName`.
512
+
513
+ Note: It is an error to call `goog.module.declareLegacyNamespace` in an ES
514
+ module, it can only be called from `goog.module` files. There is no direct way
515
+ to associate a "legacy" namespace with an ES module.
516
+
517
+ `goog.declareModuleId` should only be used to upgrade Closure files to ES
518
+ modules in place, where named exports are used.
519
+
520
+ ```
521
+ import * as goog from '../closure/goog.js';
522
+
523
+ goog.declareModuleId('my.esm');
524
+
525
+ export class Class {};
526
+ ```
527
+
528
+ ### 3.5 `goog.setTestOnly`
529
+
530
+ In a `goog.module` file the `goog.module` statement and, if present,
531
+ `goog.module.declareLegacyNamespace()` statement may optionally be followed by a
532
+ call to `goog.setTestOnly()`.
533
+
534
+ In an ES module the `import` statements may optionally be
535
+ followed by a call to `goog.setTestOnly()`.
536
+
537
+ ### 3.6 `goog.require` and `goog.requireType` statements
538
+
539
+ Imports are done with `goog.require` and `goog.requireType` statements. The
540
+ names imported by a `goog.require` statement may be used both in code and in
541
+ type annotations, while those imported by a `goog.requireType` may be used in
542
+ type annotations only.
543
+
544
+ The `goog.require` and `goog.requireType` statements form a contiguous block
545
+ with no empty lines. This block follows the `goog.module` declaration separated
546
+ [by a single empty line](#source-file-structure). The entire argument to
547
+ `goog.require` or `goog.requireType` is a namespace defined by a `goog.module`
548
+ in a separate file. `goog.require` and `goog.requireType` statements may not
549
+ appear anywhere else in the file.
550
+
551
+ Each `goog.require` or `goog.requireType` is assigned to a single constant
552
+ alias, or else destructured into several constant aliases. These aliases are the
553
+ only acceptable way to refer to dependencies in type annotations or code. Fully
554
+ qualified namespaces must not be used anywhere, except as an argument to
555
+ `goog.require` or `goog.requireType`.
556
+
557
+ **Exception**: Types, variables, and functions declared in externs files have to
558
+ use their fully qualified name in type annotations and code.
559
+
560
+ When `goog.require` is assigned to a single constant alias, it must match the
561
+ final dot-separated component of the imported module's namespace.
562
+
563
+ **Exception**: In certain cases, additional components of the namespace can be
564
+ used to form a longer alias. The resulting alias must retain the original
565
+ identifier's casing such that it still correctly identifies its type. Longer
566
+ aliases may be used to disambiguate otherwise identical aliases, or if it
567
+ significantly improves readability. In addition, a longer alias must be used to
568
+ prevent masking native types such as `Element`, `Event`, `Error`, `Map`, and
569
+ `Promise` (for a more complete list, see [Standard Built-in Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects) and
570
+ [Web APIs](https://developer.mozilla.org/en-US/docs/Web/API) at MDN).
571
+
572
+ When renaming destructured aliases, a space must follow the colon
573
+ as required in [??](#formatting-horizontal-whitespace).
574
+
575
+ A file should not contain both a `goog.require` and a `goog.requireType`
576
+ statement for the same namespace. If the imported name is used both in code and
577
+ in type annotations, it should be imported by a single `goog.require` statement.
578
+
579
+ If a module is imported only for its side effects, the call must be a
580
+ `goog.require` (not a `goog.requireType`) and assignment may be omitted. A
581
+ comment is required to explain why this is needed and suppress a compiler
582
+ warning.
583
+
584
+ The lines are sorted according to the following rules: All requires with a name
585
+ on the left hand side come first, sorted alphabetically by those names. Then
586
+ destructuring requires, again sorted by the names on the left hand side.
587
+ Finally, any require calls that are standalone (generally these are for modules
588
+ imported just for their side effects).
589
+
590
+ Tip: There’s no need to memorize this order and enforce it manually. You can
591
+ rely on your IDE to report requires
592
+ that are not sorted correctly.
593
+
594
+ If a long alias or module name would cause a line to exceed the 80-column limit,
595
+ it **must not** be wrapped: require lines are an exception to the 80-column
596
+ limit.
597
+
598
+ Example:
599
+
600
+ ```
601
+ // Standard alias style.
602
+ const asserts = goog.require('goog.asserts');
603
+ // Namespace-based alias used to disambiguate.
604
+ const testingAsserts = goog.require('goog.testing.asserts');
605
+ // Standard destructuring into aliases.
606
+ const {MyClass} = goog.require('some.package');
607
+ const {MyType} = goog.requireType('other.package');
608
+ const {clear, clone} = goog.require('goog.array');
609
+ const {Rgb} = goog.require('goog.color');
610
+ // Namespace-based destructuring into aliases used to disambiguate.
611
+ const {MyClass: NsMyClass} = goog.require('other.ns');
612
+ const {SomeType: FooSomeType} = goog.requireType('foo.types');
613
+ const {clear: objectClear, clone: objectClone} = goog.require('goog.object');
614
+ // Namespace-based destructuring into aliases used to prevent masking native type.
615
+ const {Element: RendererElement} = goog.require('web.renderer');
616
+ // Out of sequence namespace-based aliases used to improve readability.
617
+ // Also, require lines longer than 80 columns must not be wrapped.
618
+ const {SomeDataStructure: SomeDataStructureModel} = goog.requireType('identical.package.identifiers.models');
619
+ const {SomeDataStructure: SomeDataStructureProto} = goog.require('proto.identical.package.identifiers');
620
+ // goog.require without an alias in order to trigger side effects.
621
+ /** @suppress {extraRequire} Initializes MyFramework. */
622
+ goog.require('my.framework.initialization');
623
+ ```
624
+
625
+ Discouraged:
626
+
627
+ ```
628
+ // Some legacy code uses a "default export" style to export a single class, enum,
629
+ // record type, etc. Do not use this pattern in new JS.
630
+ // When using a "default export", prefer destructuring into aliases.
631
+ const MyClass = goog.require('some.package.MyClass');
632
+ const MyType = goog.requireType('some.package.MyType');
633
+ ```
634
+
635
+ ```
636
+ // If necessary to disambiguate, prefer PackageClass over SomeClass as it is
637
+ // closer to the format of the module name.
638
+ const SomeClass = goog.require('some.package.Class');
639
+ ```
640
+
641
+ Disallowed:
642
+
643
+ ```
644
+ // Extra terms must come from the namespace.
645
+ const MyClassForBizzing = goog.require('some.package.MyClass');
646
+ // Alias must include the entire final namespace component.
647
+ const MyClass = goog.require('some.package.MyClassForBizzing');
648
+ // Alias must not mask native type (should be `const JspbMap` here).
649
+ const Map = goog.require('jspb.Map');
650
+ // Don't break goog.require lines over 80 columns.
651
+ const SomeDataStructure =
652
+ goog.require('proto.identical.package.identifiers.SomeDataStructure');
653
+ // Alias must be based on the namespace.
654
+ const randomName = goog.require('something.else');
655
+ // Missing a space after the colon.
656
+ const {Foo:FooProto} = goog.require('some.package.proto.Foo');
657
+ // goog.requireType without an alias.
658
+ goog.requireType('some.package.with.a.Type');
659
+
660
+
661
+ /**
662
+ * @param {!some.unimported.Dependency} param All external types used in JSDoc
663
+ * annotations must be goog.require'd, unless declared in externs.
664
+ */
665
+ function someFunction(param) {
666
+ // goog.require lines must be at the top level before any other code.
667
+ const alias = goog.require('my.long.name.alias');
668
+ // ...
669
+ }
670
+ ```
671
+
672
+ ### 3.7 The file’s implementation
673
+
674
+ The actual implementation follows after all dependency information is declared
675
+ (separated by at least one blank line).
676
+
677
+ This may consist of any module-local declarations (constants, variables,
678
+ classes, functions, etc), as well as any exported symbols.
679
+
680
+ ## 4 Formatting
681
+
682
+ **Terminology Note**: *block-like construct* refers to the body of a class,
683
+ function, method, or brace-delimited block of code. Note that, by
684
+ [??](#features-array-literals) and [??](#features-object-literals), any array or
685
+ object literal may optionally be treated as if it were a block-like construct.
686
+
687
+ Tip: Use `clang-format`. The JavaScript community has invested effort to make
688
+ sure clang-format "does the right thing" on JavaScript files. `clang-format` has
689
+ integration with several popular editors.
690
+
691
+ ### 4.1 Braces
692
+
693
+ #### 4.1.1 Braces are used for all control structures
694
+
695
+ Braces are required for all control structures (i.e. `if`, `else`, `for`, `do`,
696
+ `while`, as well as any others), even if the body contains only a single
697
+ statement. The first statement of a non-empty block must begin on its own line.
698
+
699
+ Disallowed:
700
+
701
+ ```
702
+ if (someVeryLongCondition())
703
+ doSomething();
704
+
705
+ for (let i = 0; i < foo.length; i++) bar(foo[i]);
706
+ ```
707
+
708
+ **Exception**: A simple if statement that can fit entirely on a single line with
709
+ no wrapping (and that doesn’t have an else) may be kept on a single line with no
710
+ braces when it improves readability. This is the only case in which a control
711
+ structure may omit braces and newlines.
712
+
713
+ ```
714
+ if (shortCondition()) foo();
715
+ ```
716
+
717
+ #### 4.1.2 Nonempty blocks: K&R style
718
+
719
+ Braces follow the Kernighan and Ritchie style ("[Egyptian brackets](https://blog.codinghorror.com/new-programming-jargon/#3)") for
720
+ *nonempty* blocks and block-like constructs:
721
+
722
+ * No line break before the opening brace.
723
+ * Line break after the opening brace.
724
+ * Line break before the closing brace.
725
+ * Line break after the closing brace *if* that brace terminates a statement or
726
+ the body of a function or class statement, or a class method. Specifically,
727
+ there is *no* line break after the brace if it is followed by `else`,
728
+ `catch`, `while`, or a comma, semicolon, or right-parenthesis.
729
+
730
+ Example:
731
+
732
+ ```
733
+ class InnerClass {
734
+ constructor() {}
735
+
736
+ /** @param {number} foo */
737
+ method(foo) {
738
+ if (condition(foo)) {
739
+ try {
740
+ // Note: this might fail.
741
+ something();
742
+ } catch (err) {
743
+ recover();
744
+ }
745
+ }
746
+ }
747
+ }
748
+ ```
749
+
750
+ #### 4.1.3 Empty blocks: may be concise
751
+
752
+ An empty block or block-like construct *may* be closed immediately after it is
753
+ opened, with no characters, space, or line break in between (i.e. `{}`),
754
+ **unless** it is a part of a *multi-block statement* (one that directly contains
755
+ multiple blocks: `if`/`else` or `try`/`catch`/`finally`).
756
+
757
+ Example:
758
+
759
+ ```
760
+ function doNothing() {}
761
+ ```
762
+
763
+ Disallowed:
764
+
765
+ ```
766
+ if (condition) {
767
+ // …
768
+ } else if (otherCondition) {} else {
769
+ // …
770
+ }
771
+
772
+ try {
773
+ // …
774
+ } catch (e) {}
775
+ ```
776
+
777
+ ### 4.2 Block indentation: +2 spaces
778
+
779
+ Each time a new block or block-like construct is opened, the indent increases by
780
+ two spaces. When the block ends, the indent returns to the previous indent
781
+ level. The indent level applies to both code and comments throughout the block.
782
+ (See the example in [??](#formatting-nonempty-blocks)).
783
+
784
+ #### 4.2.1 Array literals: optionally "block-like"
785
+
786
+ Any array literal may optionally be formatted as if it were a “block-like
787
+ construct.” For example, the following are all valid (**not** an exhaustive
788
+ list):
789
+
790
+ ```
791
+ const a = [
792
+ 0,
793
+ 1,
794
+ 2,
795
+ ];
796
+
797
+ const b =
798
+ [0, 1, 2];
799
+ ```
800
+
801
+ ```
802
+ const c = [0, 1, 2];
803
+
804
+ someMethod(foo, [
805
+ 0, 1, 2,
806
+ ], bar);
807
+ ```
808
+
809
+ Other combinations are allowed, particularly when emphasizing semantic groupings
810
+ between elements, but should not be used only to reduce the vertical size of
811
+ larger arrays.
812
+
813
+ #### 4.2.2 Object literals: optionally "block-like"
814
+
815
+ Any object literal may optionally be formatted as if it were a “block-like
816
+ construct.” The same examples apply as [??](#formatting-array-literals). For
817
+ example, the following are all valid (**not** an exhaustive list):
818
+
819
+ ```
820
+ const a = {
821
+ a: 0,
822
+ b: 1,
823
+ };
824
+
825
+ const b =
826
+ {a: 0, b: 1};
827
+ ```
828
+
829
+ ```
830
+ const c = {a: 0, b: 1};
831
+
832
+ someMethod(foo, {
833
+ a: 0, b: 1,
834
+ }, bar);
835
+ ```
836
+
837
+ #### 4.2.3 Class literals
838
+
839
+ Class literals (whether declarations or expressions) are indented as blocks. Do
840
+ not add semicolons after methods, or after the closing brace of a class
841
+ *declaration* (statements—such as assignments—that contain class *expressions*
842
+ are still terminated with a semicolon). For inheritance, the `extends` keyword
843
+ is sufficient unless the superclass is templatized. Subclasses of templatized
844
+ types must explicitly specify the template type in an `@extends` JSDoc
845
+ annotation, even if it is just passing along the same template name.
846
+
847
+ Example:
848
+
849
+ ```
850
+ /** @template T */
851
+ class Foo {
852
+ /** @param {T} x */
853
+ constructor(x) {
854
+ /** @type {T} */
855
+ this.x = x;
856
+ }
857
+ }
858
+
859
+ /** @extends {Foo<number>} */
860
+ class Bar extends Foo {
861
+ constructor() {
862
+ super(42);
863
+ }
864
+ }
865
+
866
+ exports.Baz = class extends Bar {
867
+ /** @return {number} */
868
+ method() {
869
+ return this.x;
870
+ }
871
+ };
872
+ ```
873
+
874
+ ```
875
+ /** @extends {Bar} */ // <-- unnecessary @extends
876
+ exports.Baz = class extends Bar {
877
+ /** @return {number} */
878
+ method() {
879
+ return this.x;
880
+ }
881
+ };
882
+ ```
883
+
884
+ #### 4.2.4 Function expressions
885
+
886
+ When declaring an anonymous function in the list of arguments for a function
887
+ call, the body of the function is indented two spaces more than the preceding
888
+ indentation depth.
889
+
890
+ Example:
891
+
892
+ ```
893
+ prefix.something.reallyLongFunctionName('whatever', (a1, a2) => {
894
+ // Indent the function body +2 relative to indentation depth
895
+ // of the 'prefix' statement one line above.
896
+ if (a1.equals(a2)) {
897
+ someOtherLongFunctionName(a1);
898
+ } else {
899
+ andNowForSomethingCompletelyDifferent(a2.parrot);
900
+ }
901
+ });
902
+
903
+ some.reallyLongFunctionCall(arg1, arg2, arg3)
904
+ .thatsWrapped()
905
+ .then((result) => {
906
+ // Indent the function body +2 relative to the indentation depth
907
+ // of the '.then()' call.
908
+ if (result) {
909
+ result.use();
910
+ }
911
+ });
912
+ ```
913
+
914
+ #### 4.2.5 Switch statements
915
+
916
+ As with any other block, the contents of a switch block are indented +2.
917
+
918
+ After a switch label, a newline appears, and the indentation level is increased
919
+ +2, exactly as if a block were being opened. An explicit block may be used if
920
+ required by lexical scoping. The following switch label returns to the previous
921
+ indentation level, as if a block had been closed.
922
+
923
+ A blank line is optional between a `break` and the following case.
924
+
925
+ Example:
926
+
927
+ ```
928
+ switch (animal) {
929
+ case Animal.BANDERSNATCH:
930
+ handleBandersnatch();
931
+ break;
932
+
933
+ case Animal.JABBERWOCK:
934
+ handleJabberwock();
935
+ break;
936
+
937
+ default:
938
+ throw new Error('Unknown animal');
939
+ }
940
+ ```
941
+
942
+ ### 4.3 Statements
943
+
944
+ #### 4.3.1 One statement per line
945
+
946
+ Each statement is followed by a line-break.
947
+
948
+ #### 4.3.2 Semicolons are required
949
+
950
+ Every statement must be terminated with a semicolon. Relying on automatic
951
+ semicolon insertion is forbidden.
952
+
953
+ ### 4.4 Column limit: 80
954
+
955
+ JavaScript code has a column limit of 80 characters. Except as noted below, any
956
+ line that would exceed this limit must be line-wrapped, as explained in
957
+ [??](#formatting-line-wrapping).
958
+
959
+ **Exceptions:**
960
+
961
+ 1. `goog.module`, `goog.require` and `goog.requireType` statements (see
962
+ [??](#file-goog-module) and [??](#file-goog-require)).
963
+ 2. ES module `import` and `export from` statements (see
964
+ [??](#es-module-imports) and [??](#es-module-export-from)).
965
+ 3. Lines where obeying the column limit is not possible or would hinder
966
+ discoverability. Examples include:
967
+ * A long URL which should be clickable in source.
968
+ * A shell command intended to be copied-and-pasted.
969
+ * A long string literal which may need to be copied or searched for wholly
970
+ (e.g., a long file path).
971
+
972
+ ### 4.5 Line-wrapping
973
+
974
+ **Terminology Note**: *Line wrapping* is breaking a chunk of code into multiple
975
+ lines to obey column limit, where the chunk could otherwise legally fit in a
976
+ single line.
977
+
978
+ There is no comprehensive, deterministic formula showing *exactly* how to
979
+ line-wrap in every situation. Very often there are several valid ways to
980
+ line-wrap the same piece of code.
981
+
982
+ Note: While the typical reason for line-wrapping is to avoid overflowing the
983
+ column limit, even code that would in fact fit within the column limit may be
984
+ line-wrapped at the author's discretion.
985
+
986
+ Tip: Extracting a method or local variable may solve the problem without the
987
+ need to line-wrap.
988
+
989
+ #### 4.5.1 Where to break
990
+
991
+ The prime directive of line-wrapping is: prefer to break at a **higher syntactic
992
+ level**.
993
+
994
+ Preferred:
995
+
996
+ ```
997
+ currentEstimate =
998
+ calc(currentEstimate + x * currentEstimate) /
999
+ 2.0;
1000
+ ```
1001
+
1002
+ Discouraged:
1003
+
1004
+ ```
1005
+ currentEstimate = calc(currentEstimate + x *
1006
+ currentEstimate) / 2.0;
1007
+ ```
1008
+
1009
+ In the preceding example, the syntactic levels from highest to lowest are as
1010
+ follows: assignment, division, function call, parameters, number constant.
1011
+
1012
+ Operators are wrapped as follows:
1013
+
1014
+ 1. When a line is broken at an operator the break comes after the symbol. (Note
1015
+ that this is not the same practice used in Google style for Java.)
1016
+ 1. This does not apply to the "dot" (`.`), which is not actually an
1017
+ operator.
1018
+ 2. A method or constructor name stays attached to the open parenthesis (`(`)
1019
+ that follows it.
1020
+ 3. A comma (`,`) stays attached to the token that precedes it.
1021
+ 4. A line break is never added between a return and the return value as this
1022
+ would change the meaning of the code.
1023
+ 5. JSDoc annotations with type names break after "{". This is necessary as
1024
+ annotations with optional types (@const, @private, @param, etc) do not scan
1025
+ the next line.
1026
+
1027
+ > Note: The primary goal for line wrapping is to have clear code, not
1028
+ > necessarily code that fits in the smallest number of lines.
1029
+
1030
+ #### 4.5.2 Indent continuation lines at least +4 spaces
1031
+
1032
+ When line-wrapping, each line after the first (each *continuation line*) is
1033
+ indented at least +4 from the original line, unless it falls under the rules of
1034
+ block indentation.
1035
+
1036
+ When there are multiple continuation lines, indentation may be varied beyond +4
1037
+ as appropriate. In general, continuation lines at a deeper syntactic level are
1038
+ indented by larger multiples of 4, and two lines use the same indentation level
1039
+ if and only if they begin with syntactically parallel elements.
1040
+
1041
+ [??](#formatting-horizontal-alignment) addresses the discouraged practice of
1042
+ using a variable number of spaces to align certain tokens with previous lines.
1043
+
1044
+ ### 4.6 Whitespace
1045
+
1046
+ #### 4.6.1 Vertical whitespace
1047
+
1048
+ A single blank line appears:
1049
+
1050
+ 1. Between consecutive methods in a class or object literal
1051
+ 1. Exception: A blank line between two consecutive properties definitions
1052
+ in an object literal (with no other code between them) is optional. Such
1053
+ blank lines are used as needed to create *logical groupings* of fields.
1054
+ 2. Within method bodies, sparingly to create *logical groupings* of statements.
1055
+ Blank lines at the start or end of a function body are not allowed.
1056
+ 3. *Optionally* before the first or after the last method in a class or object
1057
+ literal (neither encouraged nor discouraged).
1058
+ 4. As required by other sections of this document (e.g.
1059
+ [??](#file-goog-require)).
1060
+
1061
+ *Multiple* consecutive blank lines are permitted, but never required (nor
1062
+ encouraged).
1063
+
1064
+ #### 4.6.2 Horizontal whitespace
1065
+
1066
+ Use of horizontal whitespace depends on location, and falls into three broad
1067
+ categories: *leading* (at the start of a line), *trailing* (at the end of a
1068
+ line), and *internal*. Leading whitespace (i.e., indentation) is addressed
1069
+ elsewhere. Trailing whitespace is forbidden.
1070
+
1071
+ Beyond where required by the language or other style rules, and apart from
1072
+ literals, comments, and JSDoc, a single internal ASCII space also appears in the
1073
+ following places **only**.
1074
+
1075
+ 1. Separating any reserved word (such as `if`, `for`, or `catch`) except for
1076
+ `function` and `super`, from an open parenthesis (`(`) that follows it on
1077
+ that line.
1078
+ 2. Separating any reserved word (such as `else` or `catch`) from a closing
1079
+ curly brace (`}`) that precedes it on that line.
1080
+ 3. Before any open curly brace (`{`), with two exceptions:
1081
+ 1. Before an object literal that is the first argument of a function or the
1082
+ first element in an array literal (e.g. `foo({a: [{c: d}]})`).
1083
+ 2. In a template expansion, as it is forbidden by the language (e.g. valid:
1084
+ `` `ab${1 + 2}cd` ``, invalid: `` `xy$ {3}z` ``).
1085
+ 4. On both sides of any binary or ternary operator.
1086
+ 5. After a comma (`,`) or semicolon (`;`). Note that spaces are *never* allowed
1087
+ before these characters.
1088
+ 6. After the colon (`:`) in an object literal.
1089
+ 7. On both sides of the double slash (`//`) that begins an end-of-line comment.
1090
+ Here, multiple spaces are allowed, but not required.
1091
+ 8. After an open-block comment character and on both sides of close characters
1092
+ (e.g. for short-form type declarations, casts, and parameter name comments:
1093
+ `this.foo = /** @type {number} */ (bar)`; or `function(/** string */ foo)
1094
+ {`; or `baz(/* buzz= */ true)`).
1095
+
1096
+ #### 4.6.3 Horizontal alignment: discouraged
1097
+
1098
+ **Terminology Note**: *Horizontal alignment* is the practice of adding a
1099
+ variable number of additional spaces in your code with the goal of making
1100
+ certain tokens appear directly below certain other tokens on previous lines.
1101
+
1102
+ This practice is permitted, but it is **generally discouraged** by Google Style.
1103
+ It is not even required to *maintain* horizontal alignment in places where it
1104
+ was already used.
1105
+
1106
+ Here is an example without alignment, followed by one with alignment. Both are
1107
+ allowed, but the latter is discouraged:
1108
+
1109
+ ```
1110
+ {
1111
+ tiny: 42, // this is great
1112
+ longer: 435, // this too
1113
+ };
1114
+
1115
+ {
1116
+ tiny: 42, // permitted, but future edits
1117
+ longer: 435, // may leave it unaligned
1118
+ };
1119
+ ```
1120
+
1121
+ Tip: Alignment can aid readability, but it creates problems for future
1122
+ maintenance. Consider a future change that needs to touch just one line. This
1123
+ change may leave the formerly-pleasing formatting mangled, and that is allowed.
1124
+ More often it prompts the coder (perhaps you) to adjust whitespace on nearby
1125
+ lines as well, possibly triggering a cascading series of reformattings. That
1126
+ one-line change now has a "blast radius." This can at worst result in pointless
1127
+ busywork, but at best it still corrupts version history information, slows down
1128
+ reviewers and exacerbates merge conflicts.
1129
+
1130
+ #### 4.6.4 Function arguments
1131
+
1132
+ Prefer to put all function arguments on the same line as the function name. If
1133
+ doing so would exceed the 80-column limit, the arguments must be line-wrapped in
1134
+ a readable way. To save space, you may wrap as close to 80 as possible, or put
1135
+ each argument on its own line to enhance readability. Indentation should be four
1136
+ spaces. Aligning to the parenthesis is allowed, but discouraged. Below are the
1137
+ most common patterns for argument wrapping:
1138
+
1139
+ ```
1140
+ // Arguments start on a new line, indented four spaces. Preferred when the
1141
+ // arguments don't fit on the same line with the function name (or the keyword
1142
+ // "function") but fit entirely on the second line. Works with very long
1143
+ // function names, survives renaming without reindenting, low on space.
1144
+ doSomething(
1145
+ descriptiveArgumentOne, descriptiveArgumentTwo, descriptiveArgumentThree) {
1146
+ // …
1147
+ }
1148
+
1149
+ // If the argument list is longer, wrap at 80. Uses less vertical space,
1150
+ // but violates the rectangle rule and is thus not recommended.
1151
+ doSomething(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,
1152
+ tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {
1153
+ // …
1154
+ }
1155
+
1156
+ // Four-space, one argument per line. Works with long function names,
1157
+ // survives renaming, and emphasizes each argument.
1158
+ doSomething(
1159
+ veryDescriptiveArgumentNumberOne,
1160
+ veryDescriptiveArgumentTwo,
1161
+ tableModelEventHandlerProxy,
1162
+ artichokeDescriptorAdapterIterator) {
1163
+ // …
1164
+ }
1165
+ ```
1166
+
1167
+ ### 4.7 Grouping parentheses: recommended
1168
+
1169
+ Optional grouping parentheses are omitted only when the author and reviewer
1170
+ agree that there is no reasonable chance that the code will be misinterpreted
1171
+ without them, nor would they have made the code easier to read. It is *not*
1172
+ reasonable to assume that every reader has the entire operator precedence table
1173
+ memorized.
1174
+
1175
+ Do not use unnecessary parentheses around the entire expression following
1176
+ `delete`, `typeof`, `void`, `return`, `throw`, `case`, `in`, `of`, or `yield`.
1177
+
1178
+ Parentheses are required for type casts: `/** @type {!Foo} */ (foo)`.
1179
+
1180
+ ### 4.8 Comments
1181
+
1182
+ This section addresses *implementation comments*. JSDoc is addressed separately
1183
+ in [??](#jsdoc).
1184
+
1185
+ #### 4.8.1 Block comment style
1186
+
1187
+ Block comments are indented at the same level as the surrounding code. They may
1188
+ be in `/* … */` or `//`-style. For multi-line `/* … */` comments, subsequent
1189
+ lines must start with `*` aligned with the `*` on the previous line, to make
1190
+ comments obvious with no extra context.
1191
+
1192
+ ```
1193
+ /*
1194
+ * This is
1195
+ * okay.
1196
+ */
1197
+
1198
+ // And so
1199
+ // is this.
1200
+
1201
+ /* This is fine, too. */
1202
+ ```
1203
+
1204
+ Comments are not enclosed in boxes drawn with asterisks or other characters.
1205
+
1206
+ Do not use JSDoc (`/** … */`) for implementation comments.
1207
+
1208
+ #### 4.8.2 Parameter Name Comments
1209
+
1210
+ “Parameter name” comments should be used whenever the value and method name do
1211
+ not sufficiently convey the meaning, and refactoring the method to be clearer is
1212
+ infeasible .
1213
+ Their preferred format is before the value with "=":
1214
+
1215
+ ```
1216
+ someFunction(obviousParam, /* shouldRender= */ true, /* name= */ 'hello');
1217
+ ```
1218
+
1219
+ For consistency with surrounding code you may put them after the value without
1220
+ "=":
1221
+
1222
+ ```
1223
+ someFunction(obviousParam, true /* shouldRender */, 'hello' /* name */);
1224
+ ```
1225
+
1226
+ ## 5 Language features
1227
+
1228
+ JavaScript includes many dubious (and even dangerous) features. This section
1229
+ delineates which features may or may not be used, and any additional constraints
1230
+ on their use.
1231
+
1232
+ Language features which are not discussed in this style guide may be used with
1233
+ no recommendations of their usage.
1234
+
1235
+ ### 5.1 Local variable declarations
1236
+
1237
+ #### 5.1.1 Use `const` and `let`
1238
+
1239
+ Declare all local variables with either `const` or `let`. Use `const` by
1240
+ default, unless a variable needs to be reassigned. The `var` keyword
1241
+ must not be used.
1242
+
1243
+ #### 5.1.2 One variable per declaration
1244
+
1245
+ Every local variable declaration declares only one variable: declarations such
1246
+ as `let a = 1, b = 2;` are not used.
1247
+
1248
+ #### 5.1.3 Declared when needed, initialized as soon as possible
1249
+
1250
+ Local variables are **not** habitually declared at the start of their containing
1251
+ block or block-like construct. Instead, local variables are declared close to
1252
+ the point they are first used (within reason), to minimize their scope, and
1253
+ initialized as soon as possible.
1254
+
1255
+ #### 5.1.4 Declare types as needed
1256
+
1257
+ JSDoc type annotations may be added either on the line above the declaration, or
1258
+ else inline before the variable name if no other JSDoc is present.
1259
+
1260
+ Example:
1261
+
1262
+ ```
1263
+ const /** !Array<number> */ data = [];
1264
+
1265
+ /**
1266
+ * Some description.
1267
+ * @type {!Array<number>}
1268
+ */
1269
+ const data = [];
1270
+ ```
1271
+
1272
+ Mixing inline and JSDoc styles is not allowed: the compiler will only process
1273
+ the first JsDoc and the inline annotations will be lost.
1274
+
1275
+ ```
1276
+ /** Some description. */
1277
+ const /** !Array<number> */ data = [];
1278
+ ```
1279
+
1280
+ Tip: There are many cases where the compiler can infer a templatized type but
1281
+ not its parameters. This is particularly the case when the initializing literal
1282
+ or constructor call does not include any values of the template parameter type
1283
+ (e.g., empty arrays, objects, `Map`s, or `Set`s), or if the variable is modified
1284
+ in a closure. Local variable type annotations are particularly helpful in these
1285
+ cases since otherwise the compiler will infer the template parameter as unknown.
1286
+
1287
+ ### 5.2 Array literals
1288
+
1289
+ #### 5.2.1 Use trailing commas
1290
+
1291
+ Include a trailing comma whenever there is a line break between the final
1292
+ element and the closing bracket.
1293
+
1294
+ Example:
1295
+
1296
+ ```
1297
+ const values = [
1298
+ 'first value',
1299
+ 'second value',
1300
+ ];
1301
+ ```
1302
+
1303
+ #### 5.2.2 Do not use the variadic `Array` constructor
1304
+
1305
+ The constructor is error-prone if arguments are added or removed. Use a literal
1306
+ instead.
1307
+
1308
+ Disallowed:
1309
+
1310
+ ```
1311
+ const a1 = new Array(x1, x2, x3);
1312
+ const a2 = new Array(x1, x2);
1313
+ const a3 = new Array(x1);
1314
+ const a4 = new Array();
1315
+ ```
1316
+
1317
+ This works as expected except for the third case: if `x1` is a whole number then
1318
+ `a3` is an array of size `x1` where all elements are `undefined`. If `x1` is any
1319
+ other number, then an exception will be thrown, and if it is anything else then
1320
+ it will be a single-element array.
1321
+
1322
+ Instead, write
1323
+
1324
+ ```
1325
+ const a1 = [x1, x2, x3];
1326
+ const a2 = [x1, x2];
1327
+ const a3 = [x1];
1328
+ const a4 = [];
1329
+ ```
1330
+
1331
+ Explicitly allocating an array of a given length using `new Array(length)` is
1332
+ allowed when appropriate.
1333
+
1334
+ #### 5.2.3 Non-numeric properties
1335
+
1336
+ Do not define or use non-numeric properties on an array (other than `length`).
1337
+ Use a `Map` (or `Object`) instead.
1338
+
1339
+ #### 5.2.4 Destructuring
1340
+
1341
+ Array literals may be used on the left-hand side of an assignment to perform
1342
+ destructuring (such as when unpacking multiple values from a single array or
1343
+ iterable). A final "rest" element may be included (with no space between the
1344
+ `...` and the variable name). Elements should be omitted if they are unused.
1345
+
1346
+ ```
1347
+ const [a, b, c, ...rest] = generateResults();
1348
+ let [, b,, d] = someArray;
1349
+ ```
1350
+
1351
+ Destructuring may also be used for function parameters (note that a parameter
1352
+ name is required but ignored). Always specify `[]` as the default value if a
1353
+ destructured array parameter is optional, and provide default values on the left
1354
+ hand side:
1355
+
1356
+ ```
1357
+ /** @param {!Array<number>=} param1 */
1358
+ function optionalDestructuring([a = 4, b = 2] = []) { … };
1359
+ ```
1360
+
1361
+ Disallowed:
1362
+
1363
+ ```
1364
+ function badDestructuring([a, b] = [4, 2]) { … };
1365
+ ```
1366
+
1367
+ Tip: For (un)packing multiple values into a function’s parameter or return,
1368
+ prefer object destructuring to array destructuring when possible, as it allows
1369
+ naming the individual elements and specifying a different type for each.
1370
+
1371
+ #### 5.2.5 Spread operator
1372
+
1373
+ Array literals may include the spread operator (`...`) to flatten elements out
1374
+ of one or more other iterables. The spread operator should be used instead of
1375
+ more awkward constructs with `Array.prototype`. There is no space after the
1376
+ `...`.
1377
+
1378
+ Example:
1379
+
1380
+ ```
1381
+ [...foo] // preferred over Array.prototype.slice.call(foo)
1382
+ [...foo, ...bar] // preferred over foo.concat(bar)
1383
+ ```
1384
+
1385
+ ### 5.3 Object literals
1386
+
1387
+ #### 5.3.1 Use trailing commas
1388
+
1389
+ Include a trailing comma whenever there is a line break between the final
1390
+ property and the closing brace.
1391
+
1392
+ #### 5.3.2 Do not use the `Object` constructor
1393
+
1394
+ While `Object` does not have the same problems as `Array`, it is still
1395
+ disallowed for consistency. Use an object literal (`{}` or `{a: 0, b: 1, c: 2}`)
1396
+ instead.
1397
+
1398
+ #### 5.3.3 Do not mix quoted and unquoted keys
1399
+
1400
+ Object literals may represent either *structs* (with unquoted keys and/or
1401
+ symbols) or *dicts* (with quoted and/or computed keys). Do not mix these key
1402
+ types in a single object literal.
1403
+
1404
+ Disallowed:
1405
+
1406
+ ```
1407
+ {
1408
+ width: 42, // struct-style unquoted key
1409
+ 'maxWidth': 43, // dict-style quoted key
1410
+ }
1411
+ ```
1412
+
1413
+ This also extends to passing the property name to functions, like
1414
+ `hasOwnProperty`. In particular, doing so will break in compiled code because
1415
+ the compiler cannot rename/obfuscate the string literal.
1416
+
1417
+ Disallowed:
1418
+
1419
+ ```
1420
+ /** @type {{width: number, maxWidth: (number|undefined)}} */
1421
+ const o = {width: 42};
1422
+ if (o.hasOwnProperty('maxWidth')) {
1423
+ ...
1424
+ }
1425
+ ```
1426
+
1427
+ This is best implemented as:
1428
+
1429
+ ```
1430
+ /** @type {{width: number, maxWidth: (number|undefined)}} */
1431
+ const o = {width: 42};
1432
+ if (o.maxWidth != null) {
1433
+ ...
1434
+ }
1435
+ ```
1436
+
1437
+ #### 5.3.4 Computed property names
1438
+
1439
+ Computed property names (e.g., `{['key' + foo()]: 42}`) are allowed, and are
1440
+ considered dict-style (quoted) keys (i.e., must not be mixed with non-quoted
1441
+ keys) unless the computed property is a
1442
+ [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol)
1443
+ (e.g., `[Symbol.iterator]`). Enum values may also be used for computed keys, but
1444
+ should not be mixed with non-enum keys in the same literal.
1445
+
1446
+ #### 5.3.5 Method shorthand
1447
+
1448
+ Methods can be defined on object literals using the method shorthand (`{method()
1449
+ {… }}`) in place of a colon immediately followed by a `function` or arrow
1450
+ function literal.
1451
+
1452
+ Example:
1453
+
1454
+ ```
1455
+ return {
1456
+ stuff: 'candy',
1457
+ method() {
1458
+ return this.stuff; // Returns 'candy'
1459
+ },
1460
+ };
1461
+ ```
1462
+
1463
+ Note that `this` in a method shorthand or `function` refers to the object
1464
+ literal itself whereas `this` in an arrow function refers to the scope outside
1465
+ the object literal.
1466
+
1467
+ Example:
1468
+
1469
+ ```
1470
+ class {
1471
+ getObjectLiteral() {
1472
+ this.stuff = 'fruit';
1473
+ return {
1474
+ stuff: 'candy',
1475
+ method: () => this.stuff, // Returns 'fruit'
1476
+ };
1477
+ }
1478
+ }
1479
+ ```
1480
+
1481
+ #### 5.3.6 Shorthand properties
1482
+
1483
+ Shorthand properties are allowed on object literals.
1484
+
1485
+ Example:
1486
+
1487
+ ```
1488
+ const foo = 1;
1489
+ const bar = 2;
1490
+ const obj = {
1491
+ foo,
1492
+ bar,
1493
+ method() { return this.foo + this.bar; },
1494
+ };
1495
+ assertEquals(3, obj.method());
1496
+ ```
1497
+
1498
+ #### 5.3.7 Destructuring
1499
+
1500
+ Object destructuring patterns may be used on the left-hand side of an assignment
1501
+ to perform destructuring and unpack multiple values from a single object.
1502
+
1503
+ Destructured objects may also be used as function parameters, but should be kept
1504
+ as simple as possible: a single level of unquoted shorthand properties. Deeper
1505
+ levels of nesting and computed properties may not be used in parameter
1506
+ destructuring. Specify any default values in the left-hand-side of the
1507
+ destructured parameter (`{str = 'some default'} = {}`, rather than
1508
+ `{str} = {str: 'some default'}`), and if a
1509
+ destructured object is itself optional, it must default to `{}`. The JSDoc for
1510
+ the destructured parameter may be given any name (the name is unused but is
1511
+ required by the compiler).
1512
+
1513
+ Example:
1514
+
1515
+ ```
1516
+ /**
1517
+ * @param {string} ordinary
1518
+ * @param {{num: (number|undefined), str: (string|undefined)}=} param1
1519
+ * num: The number of times to do something.
1520
+ * str: A string to do stuff to.
1521
+ */
1522
+ function destructured(ordinary, {num, str = 'some default'} = {}) {}
1523
+ ```
1524
+
1525
+ Disallowed:
1526
+
1527
+ ```
1528
+ /** @param {{x: {num: (number|undefined), str: (string|undefined)}}} param1 */
1529
+ function nestedTooDeeply({x: {num, str}}) {};
1530
+ /** @param {{num: (number|undefined), str: (string|undefined)}=} param1 */
1531
+ function nonShorthandProperty({num: a, str: b} = {}) {};
1532
+ /** @param {{a: number, b: number}} param1 */
1533
+ function computedKey({a, b, [a + b]: c}) {};
1534
+ /** @param {{a: number, b: string}=} param1 */
1535
+ function nontrivialDefault({a, b} = {a: 2, b: 4}) {};
1536
+ ```
1537
+
1538
+ Destructuring may also be used for `goog.require` statements, and in this case
1539
+ must not be wrapped: the entire statement occupies one line, regardless of how
1540
+ long it is (see [??](#file-goog-require)).
1541
+
1542
+ #### 5.3.8 Enums
1543
+
1544
+ Enumerations are defined by adding the `@enum` annotation to an object literal.
1545
+ Enums must be module-local or assigned directly on `exports`, not nested under a
1546
+ type or object.
1547
+
1548
+ Additional properties may not be added to an enum after it is defined. Enums
1549
+ must be constant. All enum values must be either a string literal or a number.
1550
+
1551
+ ```
1552
+ /**
1553
+ * Supported temperature scales.
1554
+ * @enum {string}
1555
+ */
1556
+ const TemperatureScale = {
1557
+ CELSIUS: 'celsius',
1558
+ FAHRENHEIT: 'fahrenheit',
1559
+ };
1560
+
1561
+ /**
1562
+ * An enum with two values.
1563
+ * @enum {number}
1564
+ */
1565
+ const Value = {
1566
+ /** The value used shall have been the first. */
1567
+ FIRST_VALUE: 1,
1568
+ /** The second among two values. */
1569
+ SECOND_VALUE: 2,
1570
+ };
1571
+ ```
1572
+
1573
+ For string enums, all values must be statically initialized and not computed
1574
+ using arithmetic operators, template literal substitution, function calls or
1575
+ even a variable reference.
1576
+
1577
+ ```
1578
+ const ABSOLUTE_ZERO = '-273°F';
1579
+
1580
+ /**
1581
+ * Not supported computed values in string enum.
1582
+ * @enum {string}
1583
+ */
1584
+ const TemperatureInFahrenheit = {
1585
+ MIN_POSSIBLE: ABSOLUTE_ZERO,
1586
+ ZERO_FAHRENHEIT: 0 + '°F',
1587
+ ONE_FAHRENHEIT: `${Values.FIRST_VALUE}°F`,
1588
+ TWO_FAHRENHEIT: Values.SECOND_VALUE + '°F',
1589
+ SOME_FAHRENHEIT: getTemperatureInFahrenheit() + '°F',
1590
+ };
1591
+ ```
1592
+
1593
+ Note: Although TypeScript supports a few more patterns for enum values (e.g `A:
1594
+ 'a'+'b'`, etc), the restriction of only allowing string literals and numbers for
1595
+ enum values is to aid migration to TypeScript. For complex values consider using
1596
+ a const object without `@enum`.
1597
+
1598
+ ### 5.4 Classes
1599
+
1600
+ #### 5.4.1 Constructors
1601
+
1602
+ Constructors are optional. Subclass constructors must call `super()` before
1603
+ setting any fields or otherwise accessing `this`. Interfaces should declare
1604
+ non-method properties in the constructor.
1605
+
1606
+ #### 5.4.2 Fields
1607
+
1608
+ Define all of a concrete object’s fields (i.e. all properties other than
1609
+ methods) in the constructor. Annotate fields that are never reassigned with
1610
+ `@const` (these need not be deeply immutable). Annotate non-public fields with
1611
+ the proper visibility annotation (`@private`, `@protected`, `@package`).
1612
+ `@private` fields' names may optionally end with an underscore. Fields must not
1613
+ be defined within a nested scope in the constructor nor on a concrete class's
1614
+ `prototype`.
1615
+
1616
+ Example:
1617
+
1618
+ ```
1619
+ class Foo {
1620
+ constructor() {
1621
+ /** @private @const {!Bar} */
1622
+ this.bar_ = computeBar();
1623
+
1624
+ /** @protected @const {!Baz} */
1625
+ this.baz = computeBaz();
1626
+ }
1627
+ }
1628
+ ```
1629
+
1630
+ Tip: Properties should never be added to or removed from an instance after the
1631
+ constructor is finished, since it significantly hinders VMs’ ability to
1632
+ optimize. If necessary, fields that are initialized later should be explicitly
1633
+ set to `undefined` in the constructor to prevent later shape changes. Adding
1634
+ `@struct` to an object will check that undeclared properties are not
1635
+ added/accessed. Classes have this added by default.
1636
+
1637
+ #### 5.4.3 Computed properties
1638
+
1639
+ Computed properties may only be used in classes when the property is a symbol.
1640
+ Dict-style properties (that is, quoted or computed non-symbol keys, as defined
1641
+ in [??](#features-objects-mixing-keys)) are not allowed. A `[Symbol.iterator]`
1642
+ method should be defined for any classes that are logically iterable. Beyond
1643
+ this, `Symbol` should be used sparingly.
1644
+
1645
+ Tip: be careful of using any other built-in symbols (e.g.,
1646
+ `Symbol.isConcatSpreadable`) as they are not polyfilled by the compiler and will
1647
+ therefore not work in older browsers.
1648
+
1649
+ #### 5.4.4 Static methods
1650
+
1651
+ Where it does not interfere with readability, prefer module-local functions over
1652
+ private static methods.
1653
+
1654
+ Code should not rely on dynamic dispatch of static methods, because it
1655
+ interferes with Closure Compiler optimizations. Static methods should only be
1656
+ called on the base class itself. Static methods should not be called on
1657
+ variables containing a dynamic instance that may be either the constructor or a
1658
+ subclass constructor (and must be defined with `@nocollapse` if this is done),
1659
+ and must not be called directly on a subclass that doesn’t define the method
1660
+ itself. Do not access `this` in static methods.
1661
+
1662
+ Disallowed:
1663
+
1664
+ ```
1665
+ // Context for the examples below; by itself this code is allowed.
1666
+ class Base {
1667
+ /** @nocollapse */ static foo() {}
1668
+ }
1669
+ class Sub extends Base {}
1670
+
1671
+ // discouraged: don't call static methods dynamically
1672
+ function callFoo(cls) { cls.foo(); }
1673
+
1674
+ // Disallowed: don't call static methods on subclasses that don't define it themselves
1675
+ Sub.foo();
1676
+
1677
+ // Disallowed: don't access this in static methods.
1678
+ class Clazz {
1679
+ static foo() {
1680
+ return this.staticField;
1681
+ }
1682
+ }
1683
+ Class.staticField = 1;
1684
+ ```
1685
+
1686
+ #### 5.4.5 Old-style class declarations
1687
+
1688
+ While ES6 classes are preferred, there are cases where ES6 classes may not be
1689
+ feasible. For example:
1690
+
1691
+ 1. If there exist or will exist subclasses, including frameworks that create
1692
+ subclasses, that cannot be immediately changed to use ES6 class syntax. If
1693
+ such a class were to use ES6 syntax, all downstream subclasses not using ES6
1694
+ class syntax would need to be modified.
1695
+ 2. Frameworks that require a known `this` value before calling the superclass
1696
+ constructor, since constructors with ES6 super classes do not have access to
1697
+ the instance `this` value until the call to `super` returns.
1698
+
1699
+ In all other ways the style guide still applies to this code: `let`, `const`,
1700
+ default parameters, rest, and arrow functions should all be used when
1701
+ appropriate.
1702
+
1703
+ `goog.defineClass` allows for a class-like definition similar to ES6 class
1704
+ syntax:
1705
+
1706
+ ```
1707
+ let C = goog.defineClass(S, {
1708
+ /**
1709
+ * @param {string} value
1710
+ */
1711
+ constructor(value) {
1712
+ S.call(this, 2);
1713
+ /** @const */
1714
+ this.prop = value;
1715
+ },
1716
+
1717
+ /**
1718
+ * @param {string} param
1719
+ * @return {number}
1720
+ */
1721
+ method(param) {
1722
+ return 0;
1723
+ },
1724
+ });
1725
+ ```
1726
+
1727
+ Alternatively, while `goog.defineClass` should be preferred for all new code,
1728
+ more traditional syntax is also allowed.
1729
+
1730
+ ```
1731
+ /**
1732
+ * @constructor @extends {S}
1733
+ * @param {string} value
1734
+ */
1735
+ function C(value) {
1736
+ S.call(this, 2);
1737
+ /** @const */
1738
+ this.prop = value;
1739
+ }
1740
+ goog.inherits(C, S);
1741
+
1742
+ /**
1743
+ * @param {string} param
1744
+ * @return {number}
1745
+ */
1746
+ C.prototype.method = function(param) {
1747
+ return 0;
1748
+ };
1749
+ ```
1750
+
1751
+ Per-instance properties should be defined in the constructor after the call to
1752
+ the super class constructor, if there is a super class. Methods should be
1753
+ defined on the prototype of the constructor.
1754
+
1755
+ Defining constructor prototype hierarchies correctly is harder than it first
1756
+ appears! For that reason, it is best to use `goog.inherits` from
1757
+ [the Closure Library](http://code.google.com/closure/library/) .
1758
+
1759
+ #### 5.4.6 Do not manipulate `prototype`s directly
1760
+
1761
+ The `class` keyword allows clearer and more readable class definitions than
1762
+ defining `prototype` properties. Ordinary implementation code has no business
1763
+ manipulating these objects, though they are still useful for defining classes as
1764
+ defined in [??](#features-classes-old-style). Mixins and modifying the
1765
+ prototypes of builtin objects are explicitly forbidden.
1766
+
1767
+ **Exception**: Framework code (such as Polymer, or Angular) may need to use `prototype`s, and should not resort
1768
+ to even-worse workarounds to avoid doing so.
1769
+
1770
+ #### 5.4.7 Getters and Setters
1771
+
1772
+ Do not use [JavaScript getter and setter properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get). They are potentially
1773
+ surprising and difficult to reason about, and have limited support in the
1774
+ compiler. Provide ordinary methods instead.
1775
+
1776
+ **Exception**: there are situations where defining a getter or setter is
1777
+ unavoidable (e.g. data binding frameworks such as Angular and Polymer, or for
1778
+ compatibility with external APIs that cannot be adjusted). In these cases only,
1779
+ getters and setters may be used *with caution*, provided they are defined with
1780
+ the `get` and `set` shorthand method keywords or `Object.defineProperties` (not
1781
+ `Object.defineProperty`, which interferes with property renaming). Getters
1782
+ **must not** change observable state.
1783
+
1784
+ Disallowed:
1785
+
1786
+ ```
1787
+ class Foo {
1788
+ get next() { return this.nextId++; }
1789
+ }
1790
+ ```
1791
+
1792
+ #### 5.4.8 Overriding toString
1793
+
1794
+ The `toString` method may be overridden, but must always succeed and never have
1795
+ visible side effects.
1796
+
1797
+ Tip: Beware, in particular, of calling other methods from toString, since
1798
+ exceptional conditions could lead to infinite loops.
1799
+
1800
+ #### 5.4.9 Interfaces
1801
+
1802
+ Interfaces may be declared with `@interface` or `@record`. Interfaces declared
1803
+ with `@record` can be explicitly (i.e. via `@implements`) or implicitly
1804
+ implemented by a class or object literal.
1805
+
1806
+ All methods on an interface must be non-static and method bodies must be empty
1807
+ blocks. Fields must be declared as uninitialized members in the class
1808
+ constructor.
1809
+
1810
+ Example:
1811
+
1812
+ ```
1813
+ /**
1814
+ * Something that can frobnicate.
1815
+ * @record
1816
+ */
1817
+ class Frobnicator {
1818
+ constructor() {
1819
+ /** @type {number} The number of attempts before giving up. */
1820
+ this.attempts;
1821
+ }
1822
+
1823
+ /**
1824
+ * Performs the frobnication according to the given strategy.
1825
+ * @param {!FrobnicationStrategy} strategy
1826
+ */
1827
+ frobnicate(strategy) {}
1828
+ }
1829
+ ```
1830
+
1831
+ #### 5.4.10 Abstract Classes
1832
+
1833
+ Use abstract classes when appropriate. Abstract classes and methods must be
1834
+ annotated with `@abstract`. Do not use `goog.abstractMethod`. See
1835
+ [abstract classes and methods](https://github.com/google/closure-compiler/wiki/@abstract-classes-and-methods).
1836
+
1837
+ #### 5.4.11 Do not create static container classes
1838
+
1839
+ Do not use container classes with only static methods or properties for the sake
1840
+ of namespacing.
1841
+
1842
+ ```
1843
+ // container.js
1844
+ // Bad: Container is an exported class that has only static methods and fields.
1845
+ class Container {
1846
+ /** @return {number} */
1847
+ static bar() {
1848
+ return 1;
1849
+ }
1850
+ }
1851
+
1852
+ /** @const {number} */
1853
+ Container.FOO = 1;
1854
+
1855
+ exports = {Container};
1856
+ ```
1857
+
1858
+ Instead, export individual constants and functions:
1859
+
1860
+ ```
1861
+ /** @return {number} */
1862
+ exports.bar = () => {
1863
+ return 1;
1864
+ }
1865
+
1866
+ /** @const {number} */
1867
+ exports.FOO = 1;
1868
+ ```
1869
+
1870
+ #### 5.4.12 Do not define nested namespaces
1871
+
1872
+ Do not define a nested type (e.g. class, typedef, enum, interface) on another
1873
+ module-local name.
1874
+
1875
+ ```
1876
+ // foo.js
1877
+ goog.module('my.namespace');
1878
+
1879
+ class Foo {...}
1880
+
1881
+ Foo.Bar = class {...};
1882
+
1883
+ /** @enum {number} */
1884
+ Foo.Baz = {...};
1885
+
1886
+ /** @typedef {{value: number}} */
1887
+ Foo.Qux;
1888
+
1889
+ /** @interface */
1890
+ Foo.Quuz = class {...}
1891
+
1892
+ exports.Foo = Foo;
1893
+ ```
1894
+
1895
+ These values should be top-level exports. Choose clear names for these values
1896
+ (e.g. FooConverter for a Converter that could have been nested on Foo). However,
1897
+ when the module name is redundant with part of the class name, consider omitting
1898
+ the redundancy: `foo.Foo` and `foo.Converter` rather than `foo.Foo` and
1899
+ `foo.FooConverter`. Importers can add the prefix when necessary for clarity
1900
+ (e.g. `import {Converter as FooConverter} from './foo';`) but cannot easily
1901
+ remove the redundancy when importing the entire module as a namespace.
1902
+
1903
+ ```
1904
+ // foo.js
1905
+ goog.module('my.namespace');
1906
+
1907
+ class Foo {...}
1908
+
1909
+ class FooBar {...}
1910
+
1911
+ /** @enum {string} */
1912
+ let FooBaz = {...};
1913
+
1914
+ /** @typedef {{value: number}} */
1915
+ let FooQux;
1916
+
1917
+ /** @interface */
1918
+ class FooQuuz {...};
1919
+
1920
+ export = {
1921
+ Foo,
1922
+ FooBar,
1923
+ FooBaz,
1924
+ FooQux,
1925
+ FooQuuz,
1926
+ };
1927
+ ```
1928
+
1929
+ ### 5.5 Functions
1930
+
1931
+ #### 5.5.1 Top-level functions
1932
+
1933
+ Top-level functions may be defined directly on the `exports` object, or else
1934
+ declared locally and optionally exported. See [??](#file-goog-module-exports)
1935
+ for more on exports.
1936
+
1937
+ Examples:
1938
+
1939
+ ```
1940
+ /** @param {string} str */
1941
+ exports.processString = (str) => {
1942
+ // Process the string.
1943
+ };
1944
+ ```
1945
+
1946
+ ```
1947
+ /** @param {string} str */
1948
+ const processString = (str) => {
1949
+ // Process the string.
1950
+ };
1951
+
1952
+ exports = {processString};
1953
+ ```
1954
+
1955
+ #### 5.5.2 Nested functions and closures
1956
+
1957
+ Functions may contain nested function definitions. If it is useful to give the
1958
+ function a name, it should be assigned to a local `const`.
1959
+
1960
+ #### 5.5.3 Arrow functions
1961
+
1962
+ Arrow functions provide a concise function syntax and simplify scoping `this`
1963
+ for nested functions. Prefer arrow functions over the `function` keyword for
1964
+ nested functions (but see [??](#features-objects-method-shorthand)).
1965
+
1966
+ Prefer arrow functions over other `this` scoping approaches such as
1967
+ `f.bind(this)`, `goog.bind(f, this)`, and `const self = this`. Arrow functions
1968
+ are particularly useful for calling into callbacks as they permit explicitly
1969
+ specifying which parameters to pass to the callback whereas binding will blindly
1970
+ pass along all parameters.
1971
+
1972
+ The left-hand side of the arrow contains zero or more parameters. Parentheses
1973
+ around the parameters are optional if there is only a single non-destructured
1974
+ parameter. When parentheses are used, inline parameter types may be specified
1975
+ (see [??](#jsdoc-method-and-function-comments)).
1976
+
1977
+ Tip: Always using parentheses even for single-parameter arrow functions can
1978
+ avoid situations where adding parameters, but forgetting to add parentheses, may
1979
+ result in parseable code which no longer works as intended.
1980
+
1981
+ The right-hand side of the arrow contains the body of the function. By default
1982
+ the body is a block statement (zero or more statements surrounded by curly
1983
+ braces). The body may also be an implicitly returned single expression if
1984
+ either: the program logic requires returning a value, or the `void` operator
1985
+ precedes a single function or method call (using `void` ensures `undefined` is
1986
+ returned, prevents leaking values, and communicates intent). The single
1987
+ expression form is preferred if it improves readability (e.g., for short or
1988
+ simple expressions).
1989
+
1990
+ Examples:
1991
+
1992
+ ```
1993
+ /**
1994
+ * Arrow functions can be documented just like normal functions.
1995
+ * @param {number} numParam A number to add.
1996
+ * @param {string} strParam Another number to add that happens to be a string.
1997
+ * @return {number} The sum of the two parameters.
1998
+ */
1999
+ const moduleLocalFunc = (numParam, strParam) => numParam + Number(strParam);
2000
+
2001
+ // Uses the single expression syntax with `void` because the program logic does
2002
+ // not require returning a value.
2003
+ getValue((result) => void alert(`Got ${result}`));
2004
+
2005
+ class CallbackExample {
2006
+ constructor() {
2007
+ /** @private {number} */
2008
+ this.cachedValue_ = 0;
2009
+
2010
+ // For inline callbacks, you can use inline typing for parameters.
2011
+ // Uses a block statement because the value of the single expression should
2012
+ // not be returned and the expression is not a single function call.
2013
+ getNullableValue((/** ?number */ result) => {
2014
+ this.cachedValue_ = result == null ? 0 : result;
2015
+ });
2016
+ }
2017
+ }
2018
+ ```
2019
+
2020
+ Disallowed:
2021
+
2022
+ ```
2023
+ /**
2024
+ * A function with no params and no returned value.
2025
+ * This single expression body usage is illegal because the program logic does
2026
+ * not require returning a value and we're missing the `void` operator.
2027
+ */
2028
+ const moduleLocalFunc = () => anotherFunction();
2029
+ ```
2030
+
2031
+ #### 5.5.4 Generators
2032
+
2033
+ Generators enable a number of useful abstractions and may be used as needed.
2034
+
2035
+ When defining generator functions, attach the `*` to the `function` keyword when
2036
+ present, and separate it with a space from the name of the function. When using
2037
+ delegating yields, attach the `*` to the `yield` keyword.
2038
+
2039
+ Example:
2040
+
2041
+ ```
2042
+ /** @return {!Iterator<number>} */
2043
+ function* gen1() {
2044
+ yield 42;
2045
+ }
2046
+
2047
+ /** @return {!Iterator<number>} */
2048
+ const gen2 = function*() {
2049
+ yield* gen1();
2050
+ }
2051
+
2052
+ class SomeClass {
2053
+ /** @return {!Iterator<number>} */
2054
+ * gen() {
2055
+ yield 42;
2056
+ }
2057
+ }
2058
+ ```
2059
+
2060
+ #### 5.5.5 Parameter and return types
2061
+
2062
+ Function parameters and return types should usually be documented with JSDoc
2063
+ annotations. See [??](#jsdoc-method-and-function-comments) for more information.
2064
+
2065
+ ##### 5.5.5.1 Default parameters
2066
+
2067
+ Optional parameters are permitted using the equals operator in the parameter
2068
+ list. Optional parameters must include spaces on both sides of the equals
2069
+ operator, be named exactly like required parameters (i.e., not prefixed with
2070
+ `opt_`), use the `=` suffix in their JSDoc type, come after required parameters,
2071
+ and not use initializers that produce observable side effects. All optional
2072
+ parameters for concrete functions must have default values, even if that value
2073
+ is `undefined`. In contrast to concrete functions, abstract and interface
2074
+ methods must omit default parameter values.
2075
+
2076
+ Example:
2077
+
2078
+ ```
2079
+ /**
2080
+ * @param {string} required This parameter is always needed.
2081
+ * @param {string=} optional This parameter can be omitted.
2082
+ * @param {!Node=} node Another optional parameter.
2083
+ */
2084
+ function maybeDoSomething(required, optional = '', node = undefined) {}
2085
+
2086
+ /** @interface */
2087
+ class MyInterface {
2088
+ /**
2089
+ * Interface and abstract methods must omit default parameter values.
2090
+ * @param {string=} optional
2091
+ */
2092
+ someMethod(optional) {}
2093
+ }
2094
+ ```
2095
+
2096
+ Use default parameters sparingly. Prefer destructuring (as in
2097
+ [??](#features-objects-destructuring)) to create readable APIs when there are
2098
+ more than a small handful of optional parameters that do not have a natural
2099
+ order.
2100
+
2101
+ Note: Unlike Python's default parameters, it is okay to use initializers that
2102
+ return new mutable objects (such as `{}` or `[]`) because the initializer is
2103
+ evaluated each time the default value is used, so a single object won't be
2104
+ shared across invocations.
2105
+
2106
+ Tip: While arbitrary expressions including function calls may be used as
2107
+ initializers, these should be kept as simple as possible. Avoid initializers
2108
+ that expose shared mutable state, as that can easily introduce unintended
2109
+ coupling between function calls.
2110
+
2111
+ ##### 5.5.5.2 Rest parameters
2112
+
2113
+ Use a *rest* parameter instead of accessing `arguments`. Rest parameters are
2114
+ typed with a `...` prefix in their JSDoc. The rest parameter must be the last
2115
+ parameter in the list. There is no space between the `...` and the parameter
2116
+ name. Do not name the rest parameter `var_args`. Never name a local variable or
2117
+ parameter `arguments`, which confusingly shadows the built-in name.
2118
+
2119
+ Example:
2120
+
2121
+ ```
2122
+ /**
2123
+ * @param {!Array<string>} array This is an ordinary parameter.
2124
+ * @param {...number} numbers The remainder of arguments are all numbers.
2125
+ */
2126
+ function variadic(array, ...numbers) {}
2127
+ ```
2128
+
2129
+ #### 5.5.6 Generics
2130
+
2131
+ Declare generic functions and methods when necessary with `@template TYPE` in
2132
+ the JSDoc above the function or method definition.
2133
+
2134
+ #### 5.5.7 Spread operator
2135
+
2136
+ Function calls may use the spread operator (`...`). Prefer the spread operator
2137
+ to `Function.prototype.apply` when an array or iterable is unpacked into
2138
+ multiple parameters of a variadic function. There is no space after the `...`.
2139
+
2140
+ Example:
2141
+
2142
+ ```
2143
+ function myFunction(...elements) {}
2144
+ myFunction(...array, ...iterable, ...generator());
2145
+ ```
2146
+
2147
+ ### 5.6 String literals
2148
+
2149
+ #### 5.6.1 Use single quotes
2150
+
2151
+ Ordinary string literals are delimited with single quotes (`'`), rather than
2152
+ double quotes (`"`).
2153
+
2154
+ Tip: if a string contains a single quote character, consider using a template
2155
+ string to avoid having to escape the quote.
2156
+
2157
+ Ordinary string literals may not span multiple lines.
2158
+
2159
+ #### 5.6.2 Template literals
2160
+
2161
+ Use template literals (delimited with `` ` ``) over complex string
2162
+ concatenation, particularly if multiple string literals are involved. Template
2163
+ literals may span multiple lines.
2164
+
2165
+ If a template literal spans multiple lines, it does not need to follow the
2166
+ indentation of the enclosing block, though it may if the added whitespace does
2167
+ not matter.
2168
+
2169
+ Example:
2170
+
2171
+ ```
2172
+ function arithmetic(a, b) {
2173
+ return `Here is a table of arithmetic operations:
2174
+ ${a} + ${b} = ${a + b}
2175
+ ${a} - ${b} = ${a - b}
2176
+ ${a} * ${b} = ${a * b}
2177
+ ${a} / ${b} = ${a / b}`;
2178
+ }
2179
+ ```
2180
+
2181
+ #### 5.6.3 No line continuations
2182
+
2183
+ Do not use *line continuations* (that is, ending a line inside a string literal
2184
+ with a backslash) in either ordinary or template string literals. Even though
2185
+ ES5 allows this, it can lead to tricky errors if any trailing whitespace comes
2186
+ after the slash, and is less obvious to readers.
2187
+
2188
+ Disallowed:
2189
+
2190
+ ```
2191
+ const longString = 'This is a very long string that far exceeds the 80 \
2192
+ column limit. It unfortunately contains long stretches of spaces due \
2193
+ to how the continued lines are indented.';
2194
+ ```
2195
+
2196
+ Instead, write
2197
+
2198
+ ```
2199
+ const longString = 'This is a very long string that far exceeds the 80 ' +
2200
+ 'column limit. It does not contain long stretches of spaces since ' +
2201
+ 'the concatenated strings are cleaner.';
2202
+ ```
2203
+
2204
+ ### 5.7 Number literals
2205
+
2206
+ Numbers may be specified in decimal, hex, octal, or binary. Use exactly `0x`,
2207
+ `0o`, and `0b` prefixes, with lowercase letters, for hex, octal, and binary,
2208
+ respectively. Never include a leading zero unless it is immediately followed by
2209
+ `x`, `o`, or `b`.
2210
+
2211
+ ### 5.8 Control structures
2212
+
2213
+ #### 5.8.1 For loops
2214
+
2215
+ With ES6, the language now has three different kinds of `for` loops. All may be
2216
+ used, though `for`-`of` loops should be preferred when possible.
2217
+
2218
+ `for`-`in` loops may only be used on dict-style objects (see
2219
+ [??](#features-objects-mixing-keys)), and should not be used to iterate over an
2220
+ array. `Object.prototype.hasOwnProperty` should be used in `for`-`in` loops to
2221
+ exclude unwanted prototype properties. Prefer `for`-`of` and `Object.keys` over
2222
+ `for`-`in` when possible.
2223
+
2224
+ #### 5.8.2 Exceptions
2225
+
2226
+ Exceptions are an important part of the language and should be used whenever
2227
+ exceptional cases occur. Always throw `Error`s or subclasses of `Error`: never
2228
+ throw string literals or other objects. Always use `new` when constructing an
2229
+ `Error`.
2230
+
2231
+ This treatment extends to `Promise` rejection values as `Promise.reject(obj)` is
2232
+ equivalent to `throw obj;` in async functions.
2233
+
2234
+ Custom exceptions provide a great way to convey additional error information
2235
+ from functions. They should be defined and used wherever the native `Error` type
2236
+ is insufficient.
2237
+
2238
+ Prefer throwing exceptions over ad-hoc error-handling approaches (such as
2239
+ passing an error container reference type, or returning an object with an error
2240
+ property).
2241
+
2242
+ ##### 5.8.2.1 Empty catch blocks
2243
+
2244
+ It is very rarely correct to do nothing in response to a caught exception. When
2245
+ it truly is appropriate to take no action whatsoever in a catch block, the
2246
+ reason this is justified is explained in a comment.
2247
+
2248
+ ```
2249
+ try {
2250
+ return handleNumericResponse(response);
2251
+ } catch (ok) {
2252
+ // it's not numeric; that's fine, just continue
2253
+ }
2254
+ return handleTextResponse(response);
2255
+ ```
2256
+
2257
+ Disallowed:
2258
+
2259
+ ```
2260
+ try {
2261
+ shouldFail();
2262
+ fail('expected an error');
2263
+ } catch (expected) {
2264
+ }
2265
+ ```
2266
+
2267
+ Tip: Unlike in some other languages, patterns like the above simply don’t work
2268
+ since this will catch the error thrown by `fail`. Use `assertThrows()` instead.
2269
+
2270
+ #### 5.8.3 Switch statements
2271
+
2272
+ Terminology Note: Inside the braces of a switch block are one or more statement
2273
+ groups. Each statement group consists of one or more switch labels (either `case
2274
+ FOO:` or `default:`), followed by one or more statements.
2275
+
2276
+ ##### 5.8.3.1 Fall-through: commented
2277
+
2278
+ Within a switch block, each statement group either terminates abruptly (with a
2279
+ `break`, `return` or `throw`n exception), or is marked with a comment to
2280
+ indicate that execution will or might continue into the next statement group.
2281
+ Any comment that communicates the idea of fall-through is sufficient (typically
2282
+ `// fall through`). This special comment is not required in the last statement
2283
+ group of the switch block.
2284
+
2285
+ Example:
2286
+
2287
+ ```
2288
+ switch (input) {
2289
+ case 1:
2290
+ case 2:
2291
+ prepareOneOrTwo();
2292
+ // fall through
2293
+ case 3:
2294
+ handleOneTwoOrThree();
2295
+ break;
2296
+ default:
2297
+ handleLargeNumber(input);
2298
+ }
2299
+ ```
2300
+
2301
+ ##### 5.8.3.2 The `default` case is present
2302
+
2303
+ Each switch statement includes a `default` statement group, even if it contains
2304
+ no code. The `default` statement group must be last.
2305
+
2306
+ ### 5.9 this
2307
+
2308
+ Only use `this` in class constructors and methods, in arrow functions defined
2309
+ within class constructors and methods, or in functions that have an explicit
2310
+ `@this` declared in the immediately-enclosing function’s JSDoc.
2311
+
2312
+ Never use `this` to refer to the global object, the context of an `eval`, the
2313
+ target of an event, or unnecessarily `call()`ed or `apply()`ed functions.
2314
+
2315
+ ### 5.10 Equality Checks
2316
+
2317
+ Use identity operators (`===`/`!==`) except in the cases documented below.
2318
+
2319
+ #### 5.10.1 Exceptions Where Coercion is Desirable
2320
+
2321
+ Catching both `null` and `undefined` values:
2322
+
2323
+ ```
2324
+ if (someObjectOrPrimitive == null) {
2325
+ // Checking for null catches both null and undefined for objects and
2326
+ // primitives, but does not catch other falsy values like 0 or the empty
2327
+ // string.
2328
+ }
2329
+ ```
2330
+
2331
+ ### 5.11 Disallowed features
2332
+
2333
+ #### 5.11.1 with
2334
+
2335
+ Do not use the `with` keyword. It makes your code harder to understand and has
2336
+ been banned in strict mode since ES5.
2337
+
2338
+ #### 5.11.2 Dynamic code evaluation
2339
+
2340
+ Do not use `eval` or the `Function(...string)` constructor (except for code
2341
+ loaders). These features are potentially dangerous and simply do not work in CSP
2342
+ environments.
2343
+
2344
+ #### 5.11.3 Automatic semicolon insertion
2345
+
2346
+ Always terminate statements with semicolons (except function and class
2347
+ declarations, as noted above).
2348
+
2349
+ #### 5.11.4 Non-standard features
2350
+
2351
+ Do not use non-standard features. This includes old features that have been
2352
+ removed (e.g., `WeakMap.clear`), new features that are not yet standardized
2353
+ (e.g., the current TC39 working draft, proposals at any stage, or proposed but
2354
+ not-yet-complete web standards), or proprietary features that are only
2355
+ implemented in some browsers. Use only features defined in the current ECMA-262
2356
+ or WHATWG standards. (Note that projects writing against specific APIs, such as
2357
+ Chrome extensions or Node.js, can obviously use those APIs). Non-standard
2358
+ language “extensions” (such as those provided by some external transpilers) are
2359
+ forbidden.
2360
+
2361
+ #### 5.11.5 Wrapper objects for primitive types
2362
+
2363
+ Never use `new` on the primitive object wrappers (`Boolean`, `Number`, `String`,
2364
+ `Symbol`), nor include them in type annotations.
2365
+
2366
+ Disallowed:
2367
+
2368
+ ```
2369
+ const /** Boolean */ x = new Boolean(false);
2370
+ if (x) alert(typeof x); // alerts 'object' - WAT?
2371
+ ```
2372
+
2373
+ The wrappers may be called as functions for coercing (which is preferred over
2374
+ using `+` or concatenating the empty string) or creating symbols.
2375
+
2376
+ Example:
2377
+
2378
+ ```
2379
+ const /** boolean */ x = Boolean(0);
2380
+ if (!x) alert(typeof x); // alerts 'boolean', as expected
2381
+ ```
2382
+
2383
+ #### 5.11.6 Modifying builtin objects
2384
+
2385
+ Never modify builtin types, either by adding methods to their constructors or to
2386
+ their prototypes. Avoid depending on libraries that do this. Note that the
2387
+ JSCompiler’s runtime library will provide standards-compliant polyfills where
2388
+ possible; nothing else may modify builtin objects.
2389
+
2390
+ Do not add symbols to the global object unless absolutely necessary (e.g.
2391
+ required by a third-party API).
2392
+
2393
+ #### 5.11.7 Omitting `()` when invoking a constructor
2394
+
2395
+ Never invoke a constructor in a `new` statement without using parentheses `()`.
2396
+
2397
+ Disallowed:
2398
+
2399
+ ```
2400
+ new Foo;
2401
+ ```
2402
+
2403
+ Use instead:
2404
+
2405
+ ```
2406
+ new Foo();
2407
+ ```
2408
+
2409
+ Omitting parentheses can lead to subtle mistakes. These two lines are not
2410
+ equivalent:
2411
+
2412
+ ```
2413
+ new Foo().Bar();
2414
+ new Foo.Bar();
2415
+ ```
2416
+
2417
+ ## 6 Naming
2418
+
2419
+ ### 6.1 Rules common to all identifiers
2420
+
2421
+ Identifiers use only ASCII letters and digits, and, in a small number of cases
2422
+ noted below, underscores and very rarely (when required by frameworks like
2423
+ Angular) dollar signs.
2424
+
2425
+ Give as descriptive a name as possible, within reason. Do not worry about saving
2426
+ horizontal space as it is far more important to make your code immediately
2427
+ understandable by a new reader. Do not use abbreviations that are ambiguous or
2428
+ unfamiliar to readers outside your project, and do not abbreviate by deleting
2429
+ letters within a word.
2430
+
2431
+ ```
2432
+ errorCount // No abbreviation.
2433
+ dnsConnectionIndex // Most people know what "DNS" stands for.
2434
+ referrerUrl // Ditto for "URL".
2435
+ customerId // "Id" is both ubiquitous and unlikely to be misunderstood.
2436
+ ```
2437
+
2438
+ Disallowed:
2439
+
2440
+ ```
2441
+ n // Meaningless.
2442
+ nErr // Ambiguous abbreviation.
2443
+ nCompConns // Ambiguous abbreviation.
2444
+ wgcConnections // Only your group knows what this stands for.
2445
+ pcReader // Lots of things can be abbreviated "pc".
2446
+ cstmrId // Deletes internal letters.
2447
+ kSecondsPerDay // Do not use Hungarian notation.
2448
+ ```
2449
+
2450
+ **Exception**: Variables that are in scope for 10 lines or fewer, including
2451
+ arguments that are *not* part of an exported API, *may* use short (e.g. single
2452
+ letter) variable names.
2453
+
2454
+ ### 6.2 Rules by identifier type
2455
+
2456
+ #### 6.2.1 Package names
2457
+
2458
+ Package names are all `lowerCamelCase`. For example, `my.exampleCode.deepSpace`,
2459
+ but not `my.examplecode.deepspace` or
2460
+ `my.example_code.deep_space`.
2461
+
2462
+ **Exception**: The package name may conform to TypeScript's path-based pattern. This is
2463
+ typically all lower case with underscores where present in filenames.
2464
+
2465
+ #### 6.2.2 Class names
2466
+
2467
+ Class, interface, record, and typedef names are written in `UpperCamelCase`.
2468
+ Unexported classes are simply locals: they are not marked `@private`.
2469
+
2470
+ Type names are typically nouns or noun phrases. For example, `Request`,
2471
+ `ImmutableView`, or `VisibilityMode`. Additionally, interface names may
2472
+ sometimes be adjectives or adjective phrases instead (for example, `Readable`).
2473
+
2474
+ #### 6.2.3 Method names
2475
+
2476
+ Method names are written in `lowerCamelCase`. Names for `@private` methods may
2477
+ optionally end with a trailing underscore.
2478
+
2479
+ Method names are typically verbs or verb phrases. For example, `sendMessage` or
2480
+ `stop_`. Getter and setter methods for properties are never required, but if
2481
+ they are used they should be named `getFoo` (or optionally `isFoo` or `hasFoo`
2482
+ for booleans), or `setFoo(value)` for setters.
2483
+
2484
+ Underscores may also appear in JsUnit test method names to separate logical
2485
+ components of the name. One typical pattern is
2486
+ `test<MethodUnderTest>_<state>_<expectedOutcome>`, for example
2487
+ `testPop_emptyStack_throws`. There is no One Correct Way to name test methods.
2488
+
2489
+ #### 6.2.4 Enum names
2490
+
2491
+ Enum names are written in `UpperCamelCase`, similar to classes, and should
2492
+ generally be singular nouns. Individual items within the enum are named in
2493
+ `CONSTANT_CASE`.
2494
+
2495
+ #### 6.2.5 Constant names
2496
+
2497
+ Constant names use `CONSTANT_CASE`: all uppercase letters, with words separated
2498
+ by underscores. There is no reason for a constant to be named with a trailing
2499
+ underscore, since private static properties can be replaced by (implicitly
2500
+ private) module locals.
2501
+
2502
+ ##### 6.2.5.1 Definition of “constant”
2503
+
2504
+ Every constant is a `@const` static property or a module-local `const`
2505
+ declaration, but not all `@const` static properties and module-local `const`s
2506
+ are constants. Before choosing constant case, consider whether the field really
2507
+ feels like a *deeply immutable* constant. For example, if any of that instance's
2508
+ observable state can change, it is almost certainly not a constant. Merely
2509
+ intending to never mutate the object is generally not enough.
2510
+
2511
+ Examples:
2512
+
2513
+ ```
2514
+ // Constants
2515
+ const NUMBER = 5;
2516
+ /** @const */ exports.NAMES = goog.debug.freeze(['Ed', 'Ann']);
2517
+ /** @enum */ exports.SomeEnum = { ENUM_CONSTANT: 'value' };
2518
+
2519
+ // Not constants
2520
+ let letVariable = 'non-const';
2521
+
2522
+ class MyClass {
2523
+ constructor() { /** @const {string} */ this.nonStatic = 'non-static'; }
2524
+ };
2525
+ /** @type {string} */
2526
+ MyClass.staticButMutable = 'not @const, can be reassigned';
2527
+
2528
+ const /** Set<string> */ mutableCollection = new Set();
2529
+
2530
+ const /** MyImmutableContainer<SomeMutableType> */ stillMutable =
2531
+ new MyImmutableContainer(mutableInner);
2532
+
2533
+ const {Foo} = goog.require('my.foo'); // mirrors imported name
2534
+
2535
+ const logger = log.getLogger('loggers.are.not.immutable');
2536
+ ```
2537
+
2538
+ Constants’ names are typically nouns or noun phrases.
2539
+
2540
+ ##### 6.2.5.2 Local aliases
2541
+
2542
+ Local aliases should be used whenever they improve readability over
2543
+ fully-qualified names. Follow the same rules as `goog.require`s
2544
+ ([??](#file-goog-require)), maintaining the last part of the aliased name.
2545
+ Aliases may also be used within functions. Aliases must be `const`.
2546
+
2547
+ Examples:
2548
+
2549
+ ```
2550
+ const staticHelper = importedNamespace.staticHelper;
2551
+ const CONSTANT_NAME = ImportedClass.CONSTANT_NAME;
2552
+ const {assert, assertInstanceof} = asserts;
2553
+ ```
2554
+
2555
+ #### 6.2.6 Non-constant field names
2556
+
2557
+ Non-constant field names (static or otherwise) are written in `lowerCamelCase`,
2558
+ with an optional trailing underscore for private fields.
2559
+
2560
+ These names are typically nouns or noun phrases. For example, `computedValues`
2561
+ or `index_`.
2562
+
2563
+ #### 6.2.7 Parameter names
2564
+
2565
+ Parameter names are written in `lowerCamelCase`. Note that this applies even if
2566
+ the parameter expects a constructor.
2567
+
2568
+ One-character parameter names should not be used in public methods.
2569
+
2570
+ **Exception**: When required by a third-party framework, parameter names may
2571
+ begin with a `$`. This exception does not apply to any other identifiers (e.g.
2572
+ local variables or properties).
2573
+
2574
+ #### 6.2.8 Local variable names
2575
+
2576
+ Local variable names are written in `lowerCamelCase`, except for module-local
2577
+ (top-level) constants, as described above. Constants in function scopes are
2578
+ still named in `lowerCamelCase`. Note that `lowerCamelCase` is used
2579
+ even if the variable holds a constructor.
2580
+
2581
+ #### 6.2.9 Template parameter names
2582
+
2583
+ Template parameter names should be concise, single-word or single-letter
2584
+ identifiers, and must be all-caps, such as `TYPE` or `THIS`.
2585
+
2586
+ #### 6.2.10 Module-local names
2587
+
2588
+ Module-local names that are not exported are implicitly private. They are not
2589
+ marked `@private`. This applies to classes, functions, variables, constants,
2590
+ enums, and other module-local identifiers.
2591
+
2592
+ ### 6.3 Camel case: defined
2593
+
2594
+ Sometimes there is more than one reasonable way to convert an English phrase
2595
+ into camel case, such as when acronyms or unusual constructs like "IPv6" or
2596
+ "iOS" are present. To improve predictability, Google Style specifies the
2597
+ following (nearly) deterministic scheme.
2598
+
2599
+ Beginning with the prose form of the name:
2600
+
2601
+ 1. Convert the phrase to plain ASCII and remove any apostrophes. For example,
2602
+ "Müller's algorithm" might become "Muellers algorithm".
2603
+ 2. Divide this result into words, splitting on spaces and any remaining
2604
+ punctuation (typically hyphens).
2605
+ 1. Recommended: if any word already has a conventional camel case
2606
+ appearance in common usage, split this into its constituent parts (e.g.,
2607
+ "AdWords" becomes "ad words"). Note that a word such as "iOS" is not
2608
+ really in camel case per se; it defies any convention, so this
2609
+ recommendation does not apply.
2610
+ 3. Now lowercase everything (including acronyms), then uppercase only the first
2611
+ character of:
2612
+ 1. … each word, to yield `UpperCamelCase`, or
2613
+ 2. … each word except the first, to yield `lowerCamelCase`
2614
+ 4. Finally, join all the words into a single identifier.
2615
+
2616
+ Note that the casing of the original words is almost entirely disregarded.
2617
+
2618
+ Examples of `lowerCamelCase`:
2619
+
2620
+ | Prose form | Correct | Incorrect |
2621
+ | --- | --- | --- |
2622
+ | "XML HTTP request" | `xmlHttpRequest` | `XMLHTTPRequest` |
2623
+ | "new customer ID" | `newCustomerId` | `newCustomerID` |
2624
+ | "inner stopwatch" | `innerStopwatch` | `innerStopWatch` |
2625
+ | "supports IPv6 on iOS?" | `supportsIpv6OnIos` | `supportsIPv6OnIOS` |
2626
+ | "YouTube importer" | `youTubeImporter` | `youtubeImporter`\* |
2627
+
2628
+ \*Acceptable, but not recommended.
2629
+
2630
+ For examples of `UpperCamelCase`, uppercase the first letter of each correct
2631
+ `lowerCamelCase` example.
2632
+
2633
+ Note: Some words are ambiguously hyphenated in the English language: for example
2634
+ "nonempty" and "non-empty" are both correct, so the method names `checkNonempty`
2635
+ and `checkNonEmpty` are likewise both correct.
2636
+
2637
+ ## 7 JSDoc
2638
+
2639
+ [JSDoc](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler) is used on all classes, fields, and methods.
2640
+
2641
+ ### 7.1 General form
2642
+
2643
+ The basic formatting of JSDoc blocks is as seen in this example:
2644
+
2645
+ ```
2646
+ /**
2647
+ * Multiple lines of JSDoc text are written here,
2648
+ * wrapped normally.
2649
+ * @param {number} arg A number to do something to.
2650
+ */
2651
+ function doSomething(arg) { … }
2652
+ ```
2653
+
2654
+ or in this single-line example:
2655
+
2656
+ ```
2657
+ /** @const @private {!Foo} A short bit of JSDoc. */
2658
+ this.foo_ = foo;
2659
+ ```
2660
+
2661
+ If a single-line comment overflows into multiple lines, it must use the
2662
+ multi-line style with `/**` and `*/` on their own lines.
2663
+
2664
+ Many tools extract metadata from JSDoc comments to perform code validation and
2665
+ optimization. As such, these comments **must** be well-formed.
2666
+
2667
+ ### 7.2 Markdown
2668
+
2669
+ JSDoc is written in Markdown, though it may include HTML when necessary.
2670
+
2671
+ Note that tools that automatically extract JSDoc (e.g. [JsDossier](https://github.com/jleyba/js-dossier)) will often
2672
+ ignore plain text formatting, so if you did this:
2673
+
2674
+ ```
2675
+ /**
2676
+ * Computes weight based on three factors:
2677
+ * items sent
2678
+ * items received
2679
+ * last timestamp
2680
+ */
2681
+ ```
2682
+
2683
+ it would come out like this:
2684
+
2685
+ ```
2686
+ Computes weight based on three factors: items sent items received last timestamp
2687
+ ```
2688
+
2689
+ Instead, write a Markdown list:
2690
+
2691
+ ```
2692
+ /**
2693
+ * Computes weight based on three factors:
2694
+ *
2695
+ * - items sent
2696
+ * - items received
2697
+ * - last timestamp
2698
+ */
2699
+ ```
2700
+
2701
+ ### 7.3 JSDoc tags
2702
+
2703
+ Google style allows a subset of JSDoc tags. See
2704
+ [??](#appendices-jsdoc-tag-reference) for the complete list. Most tags must
2705
+ occupy their own line, with the tag at the beginning of the line.
2706
+
2707
+ Disallowed:
2708
+
2709
+ ```
2710
+ /**
2711
+ * The "param" tag must occupy its own line and may not be combined.
2712
+ * @param {number} left @param {number} right
2713
+ */
2714
+ function add(left, right) { ... }
2715
+ ```
2716
+
2717
+ Simple tags that do not require any additional data (such as `@private`,
2718
+ `@const`, `@final`, `@export`) may be combined onto the same line, along with an
2719
+ optional type when appropriate.
2720
+
2721
+ ```
2722
+ /**
2723
+ * Place more complex annotations (like "implements" and "template")
2724
+ * on their own lines. Multiple simple tags (like "export" and "final")
2725
+ * may be combined in one line.
2726
+ * @export @final
2727
+ * @implements {Iterable<TYPE>}
2728
+ * @template TYPE
2729
+ */
2730
+ class MyClass {
2731
+ /**
2732
+ * @param {!ObjType} obj Some object.
2733
+ * @param {number=} num An optional number.
2734
+ */
2735
+ constructor(obj, num = 42) {
2736
+ /** @private @const {!Array<!ObjType|number>} */
2737
+ this.data_ = [obj, num];
2738
+ }
2739
+ }
2740
+ ```
2741
+
2742
+ There is no hard rule for when to combine tags, or in which order, but be
2743
+ consistent.
2744
+
2745
+ For general information about annotating types in JavaScript see
2746
+ [Annotating JavaScript for the Closure Compiler](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler) and
2747
+ [Types in the Closure Type System](https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System).
2748
+
2749
+ ### 7.4 Line wrapping
2750
+
2751
+ Line-wrapped block tags are indented four spaces. Wrapped description text may
2752
+ be lined up with the description on previous lines, but this horizontal
2753
+ alignment is discouraged.
2754
+
2755
+ ```
2756
+ /**
2757
+ * Illustrates line wrapping for long param/return descriptions.
2758
+ * @param {string} foo This is a param with a description too long to fit in
2759
+ * one line.
2760
+ * @return {number} This returns something that has a description too long to
2761
+ * fit in one line.
2762
+ */
2763
+ exports.method = function(foo) {
2764
+ return 5;
2765
+ };
2766
+ ```
2767
+
2768
+ Do not indent when wrapping a `@desc` or `@fileoverview` description.
2769
+
2770
+ ### 7.5 Top/file-level comments
2771
+
2772
+ A file may have a top-level file overview. A copyright notice, author information,
2773
+ and default [visibility level](#jsdoc-visibility-annotations) are optional.
2774
+ File overviews are generally recommended whenever a
2775
+ file consists of more than a single class definition. The top level comment is
2776
+ designed to orient readers unfamiliar with the code to what is in this file. If
2777
+ present, it may provide a description of the file's contents and any
2778
+ dependencies or compatibility information. Wrapped lines are not indented.
2779
+
2780
+ Example:
2781
+
2782
+ ```
2783
+ /**
2784
+ * @fileoverview Description of file, its uses and information
2785
+ * about its dependencies.
2786
+ * @package
2787
+ */
2788
+ ```
2789
+
2790
+ ### 7.6 Class comments
2791
+
2792
+ Classes, interfaces and records must be documented with a description and any
2793
+ template parameters, implemented interfaces, visibility, or other appropriate
2794
+ tags. The class description should provide the reader with enough information to
2795
+ know how and when to use the class, as well as any additional considerations
2796
+ necessary to correctly use the class. Textual descriptions may be omitted on the
2797
+ constructor. When defining a class `@constructor` and `@extends` annotations are
2798
+ not used with the `class` keyword unless it extends a generic class. When
2799
+ defining an `@interface` or a `@record`, the `@extends` annotation is used when
2800
+ defining a subclass and the `extends` keyword is never used.
2801
+
2802
+ ```
2803
+ /**
2804
+ * A fancier event target that does cool things.
2805
+ * @implements {Iterable<string>}
2806
+ */
2807
+ class MyFancyTarget extends EventTarget {
2808
+ /**
2809
+ * @param {string} arg1 An argument that makes this more interesting.
2810
+ * @param {!Array<number>} arg2 List of numbers to be processed.
2811
+ */
2812
+ constructor(arg1, arg2) {
2813
+ // ...
2814
+ }
2815
+ };
2816
+
2817
+ /**
2818
+ * Records are also helpful.
2819
+ * @extends {Iterator<TYPE>}
2820
+ * @record
2821
+ * @template TYPE
2822
+ */
2823
+ class Listable {
2824
+ /** @return {TYPE} The next item in line to be returned. */
2825
+ next() {}
2826
+ }
2827
+ ```
2828
+
2829
+ ### 7.7 Enum and typedef comments
2830
+
2831
+ All enums and typedefs must be documented with appropriate JSDoc tags
2832
+ (`@typedef` or `@enum`) on the preceding line. Public enums and typedefs must
2833
+ also have a description. Individual enum items may be documented with a JSDoc
2834
+ comment on the preceding line.
2835
+
2836
+ ```
2837
+ /**
2838
+ * A useful type union, which is reused often.
2839
+ * @typedef {!FruitType|!FruitTypeEnum}
2840
+ */
2841
+ let CoolUnionType;
2842
+
2843
+ /**
2844
+ * Types of fruits.
2845
+ * @enum {string}
2846
+ */
2847
+ const FruitTypeEnum = {
2848
+ /** This kind is very sour. */
2849
+ SOUR: 'sour',
2850
+ /** The less-sour kind. */
2851
+ SWEET: 'sweet',
2852
+ };
2853
+ ```
2854
+
2855
+ Typedefs are useful for defining short record types, or aliases for unions,
2856
+ complex functions, or generic types. Typedefs should be avoided for record types
2857
+ with many fields, since they do not allow documenting individual fields, nor
2858
+ using templates or recursive references. For large record types, prefer
2859
+ `@record`.
2860
+
2861
+ ### 7.8 Method and function comments
2862
+
2863
+ In methods and named functions, parameter and return types must be documented,
2864
+ even in the case of same-signature `@override`s. The `this` type should be
2865
+ documented when necessary. Return type may be omitted if the function has no
2866
+ non-empty `return` statements.
2867
+
2868
+ Method, parameter, and return descriptions (but not types) may be omitted if
2869
+ they are obvious from the rest of the method’s JSDoc or from its signature.
2870
+
2871
+ Method descriptions begin with a verb phrase that describes what the method
2872
+ does. This phrase is not an imperative sentence, but instead is written in the
2873
+ third person, as if there is an implied "This method ..." before it.
2874
+
2875
+ If a method overrides a superclass method, it must include an `@override`
2876
+ annotation. For overridden methods, all `@param` and `@return` annotations must
2877
+ be specified explicitly even if no type from the superclass method is refined.
2878
+ This is to align with TypeScript.
2879
+
2880
+ ```
2881
+ /** A class that does something. */
2882
+ class SomeClass extends SomeBaseClass {
2883
+ /**
2884
+ * Operates on an instance of MyClass and returns something.
2885
+ * @param {!MyClass} obj An object that for some reason needs detailed
2886
+ * explanation that spans multiple lines.
2887
+ * @param {!OtherClass} obviousOtherClass
2888
+ * @return {boolean} Whether something occurred.
2889
+ */
2890
+ someMethod(obj, obviousOtherClass) { ... }
2891
+
2892
+ /**
2893
+ * @param {string} param
2894
+ * @return {string}
2895
+ * @override
2896
+ */
2897
+ overriddenMethod(param) { ... }
2898
+ }
2899
+
2900
+ /**
2901
+ * Demonstrates how top-level functions follow the same rules. This one
2902
+ * makes an array.
2903
+ * @param {TYPE} arg
2904
+ * @return {!Array<TYPE>}
2905
+ * @template TYPE
2906
+ */
2907
+ function makeArray(arg) { ... }
2908
+ ```
2909
+
2910
+ If you only need to document the param and return types of a function, you may
2911
+ optionally use inline JSDocs in the function's signature. These inline JSDocs
2912
+ specify the return and param types without tags.
2913
+
2914
+ ```
2915
+ function /** string */ foo(/** number */ arg) {...}
2916
+ ```
2917
+
2918
+ If you need descriptions or tags, use a single JSDoc comment above the method.
2919
+ For example, methods which return values need a `@return` tag.
2920
+
2921
+ ```
2922
+ class MyClass {
2923
+ /**
2924
+ * @param {number} arg
2925
+ * @return {string}
2926
+ */
2927
+ bar(arg) {...}
2928
+ }
2929
+ ```
2930
+
2931
+ ```
2932
+ // Illegal inline JSDocs.
2933
+
2934
+ class MyClass {
2935
+ /** @return {string} */ foo() {...}
2936
+ }
2937
+
2938
+ /** No function description allowed inline here. */ function bar() {...}
2939
+
2940
+ function /** Function description is also illegal here. */ baz() {...}
2941
+ ```
2942
+
2943
+ In anonymous functions annotations are generally optional. If the automatic type
2944
+ inference is insufficient or explicit annotation improves readability, then
2945
+ annotate param and return types like this:
2946
+
2947
+ ```
2948
+ promise.then(
2949
+ /** @return {string} */
2950
+ (/** !Array<string> */ items) => {
2951
+ doSomethingWith(items);
2952
+ return items[0];
2953
+ });
2954
+ ```
2955
+
2956
+ For function type expressions, see [??](#jsdoc-function-types).
2957
+
2958
+ ### 7.9 Property comments
2959
+
2960
+ Property types must be documented. The description may be omitted for private
2961
+ properties, if name and type provide enough documentation for understanding the
2962
+ code.
2963
+
2964
+ Publicly exported constants are commented the same way as properties.
2965
+
2966
+ ```
2967
+ /** My class. */
2968
+ class MyClass {
2969
+ /** @param {string=} someString */
2970
+ constructor(someString = 'default string') {
2971
+ /** @private @const {string} */
2972
+ this.someString_ = someString;
2973
+
2974
+ /** @private @const {!OtherType} */
2975
+ this.someOtherThing_ = functionThatReturnsAThing();
2976
+
2977
+ /**
2978
+ * Maximum number of things per pane.
2979
+ * @type {number}
2980
+ */
2981
+ this.someProperty = 4;
2982
+ }
2983
+ }
2984
+
2985
+ /**
2986
+ * The number of times we'll try before giving up.
2987
+ * @const {number}
2988
+ */
2989
+ MyClass.RETRY_COUNT = 33;
2990
+ ```
2991
+
2992
+ ### 7.10 Type annotations
2993
+
2994
+ Type annotations are found on `@param`, `@return`, `@this`, and `@type` tags,
2995
+ and optionally on `@const`, `@export`, and any visibility tags. Type annotations
2996
+ attached to JSDoc tags must always be enclosed in braces.
2997
+
2998
+ #### 7.10.1 Nullability
2999
+
3000
+ The type system defines modifiers `!` and `?` for non-null and nullable,
3001
+ respectively. These modifiers must precede the type.
3002
+
3003
+ Nullability modifiers have different requirements for different types, which
3004
+ fall into two broad categories:
3005
+
3006
+ 1. Type annotations for primitives (`string`, `number`, `boolean`, `symbol`,
3007
+ `undefined`, `null`) and literals (`{function(...): ...}` and `{{foo:
3008
+ string...}}`) are always non-nullable by default. Use the `?` modifier to
3009
+ make it nullable, but omit the redundant `!`.
3010
+ 2. Reference types (generally, anything in `UpperCamelCase`, including
3011
+ `some.namespace.ReferenceType`) refer to a class, enum, record, or typedef
3012
+ defined elsewhere. Since these types may or may not be nullable, it is
3013
+ impossible to tell from the name alone whether it is nullable or not. Always
3014
+ use explicit `?` and `!` modifiers for these types to prevent ambiguity at
3015
+ use sites.
3016
+
3017
+ Bad:
3018
+
3019
+ ```
3020
+ const /** MyObject */ myObject = null; // Non-primitive types must be annotated.
3021
+ const /** !number */ someNum = 5; // Primitives are non-nullable by default.
3022
+ const /** number? */ someNullableNum = null; // ? should precede the type.
3023
+ const /** !{foo: string, bar: number} */ record = ...; // Already non-nullable.
3024
+ const /** MyTypeDef */ def = ...; // Not sure if MyTypeDef is nullable.
3025
+
3026
+ // Not sure if object (nullable), enum (non-nullable, unless otherwise
3027
+ // specified), or typedef (depends on definition).
3028
+ const /** SomeCamelCaseName */ n = ...;
3029
+ ```
3030
+
3031
+ Good:
3032
+
3033
+ ```
3034
+ const /** ?MyObject */ myObject = null;
3035
+ const /** number */ someNum = 5;
3036
+ const /** ?number */ someNullableNum = null;
3037
+ const /** {foo: string, bar: number} */ record = ...;
3038
+ const /** !MyTypeDef */ def = ...;
3039
+ const /** ?SomeCamelCaseName */ n = ...;
3040
+ ```
3041
+
3042
+ #### 7.10.2 Type Casts
3043
+
3044
+ In cases where the compiler doesn't accurately infer the type of an expression,
3045
+ and the assertion functions in
3046
+ [goog.asserts](https://google.github.io/closure-library/api/goog.asserts.html)
3047
+ cannot remedy it, it is
3048
+ possible to tighten the type by adding a type annotation comment and enclosing
3049
+ the expression in parentheses. Note that the parentheses are required.
3050
+
3051
+ ```
3052
+ /** @type {number} */ (x)
3053
+ ```
3054
+
3055
+ #### 7.10.3 Template Parameter Types
3056
+
3057
+ Always specify template parameters. This way compiler can do a better job and it
3058
+ makes it easier for readers to understand what code does.
3059
+
3060
+ Bad:
3061
+
3062
+ ```
3063
+ const /** !Object */ users = {};
3064
+ const /** !Array */ books = [];
3065
+ const /** !Promise */ response = ...;
3066
+ ```
3067
+
3068
+ Good:
3069
+
3070
+ ```
3071
+ const /** !Object<string, !User> */ users = {};
3072
+ const /** !Array<string> */ books = [];
3073
+ const /** !Promise<!Response> */ response = ...;
3074
+
3075
+ const /** !Promise<undefined> */ thisPromiseReturnsNothingButParameterIsStillUseful = ...;
3076
+ const /** !Object<string, *> */ mapOfEverything = {};
3077
+ ```
3078
+
3079
+ Cases when template parameters should not be used:
3080
+
3081
+ * `Object` is used for type hierarchy and not as map-like structure.
3082
+
3083
+ #### 7.10.4 Function type expressions
3084
+
3085
+ **Terminology Note**: *function type expression* refers to a type annotation for
3086
+ function types with the keyword `function` in the annotation (see examples
3087
+ below).
3088
+
3089
+ Where the function definition is given, do not use a function type expression.
3090
+ Specify parameter and return types with `@param` and `@return`, or with inline
3091
+ annotations (see [??](#jsdoc-method-and-function-comments)). This includes
3092
+ anonymous functions and functions defined and assigned to a const (where the
3093
+ function jsdoc appears above the whole assignment expression).
3094
+
3095
+ Function type expressions are needed, for example, inside `@typedef`, `@param`
3096
+ or `@return`. Use it also for variables or properties of function type, if they
3097
+ are not immediately initialized with the function definition.
3098
+
3099
+ ```
3100
+ /** @private {function(string): string} */
3101
+ this.idGenerator_ = googFunctions.identity;
3102
+ ```
3103
+
3104
+ When using a function type expression, always specify the return type
3105
+ explicitly. Otherwise the default return type is "unknown" (`?`), which leads to
3106
+ strange and unexpected behavior, and is rarely what is actually desired.
3107
+
3108
+ Bad - type error, but no warning given:
3109
+
3110
+ ```
3111
+ /** @param {function()} generateNumber */
3112
+ function foo(generateNumber) {
3113
+ const /** number */ x = generateNumber(); // No compile-time type error here.
3114
+ }
3115
+
3116
+ foo(() => 'clearly not a number');
3117
+ ```
3118
+
3119
+ Good:
3120
+
3121
+ ```
3122
+ /**
3123
+ * @param {function(): *} inputFunction1 Can return any type.
3124
+ * @param {function(): undefined} inputFunction2 Definitely doesn't return
3125
+ * anything.
3126
+ * NOTE: the return type of `foo` itself is safely implied to be {undefined}.
3127
+ */
3128
+ function foo(inputFunction1, inputFunction2) {...}
3129
+ ```
3130
+
3131
+ #### 7.10.5 Whitespace
3132
+
3133
+ Within a type annotation, a single space or line break is required after each
3134
+ comma or colon. Additional line breaks may be inserted to improve readability or
3135
+ avoid exceeding the column limit. These breaks should be chosen and indented
3136
+ following the applicable guidelines (e.g. [??](#formatting-line-wrapping) and
3137
+ [??](#formatting-block-indentation)). No other whitespace is allowed in type
3138
+ annotations.
3139
+
3140
+ Good:
3141
+
3142
+ ```
3143
+ /** @type {function(string): number} */
3144
+
3145
+ /** @type {{foo: number, bar: number}} */
3146
+
3147
+ /** @type {number|string} */
3148
+
3149
+ /** @type {!Object<string, string>} */
3150
+
3151
+ /** @type {function(this: Object<string, string>, number): string} */
3152
+
3153
+ /**
3154
+ * @type {function(
3155
+ * !SuperDuperReallyReallyLongTypedefThatForcesTheLineBreak,
3156
+ * !OtherVeryLongTypedef): string}
3157
+ */
3158
+
3159
+ /**
3160
+ * @type {!SuperDuperReallyReallyLongTypedefThatForcesTheLineBreak|
3161
+ * !OtherVeryLongTypedef}
3162
+ */
3163
+ ```
3164
+
3165
+ Bad:
3166
+
3167
+ ```
3168
+ // Only put a space after the colon
3169
+ /** @type {function(string) : number} */
3170
+
3171
+ // Put spaces after colons and commas
3172
+ /** @type {{foo:number,bar:number}} */
3173
+
3174
+ // No space in union types
3175
+ /** @type {number | string} */
3176
+ ```
3177
+
3178
+ ### 7.11 Visibility annotations
3179
+
3180
+ Visibility annotations (`@private`, `@package`, `@protected`) may be specified
3181
+ in a `@fileoverview` block, or on any exported symbol or property. Do not
3182
+ specify visibility for local variables, whether within a function or at the top
3183
+ level of a module. `@private` names may optionally end with an underscore.
3184
+
3185
+ ## 8 Policies
3186
+
3187
+ ### 8.1 Issues unspecified by Google Style: Be Consistent!
3188
+
3189
+ For any style question that isn't settled definitively by this specification,
3190
+ prefer to do what the other code in the same file is already doing. If that
3191
+ doesn't resolve the question, consider emulating the other files in the same
3192
+ package.
3193
+
3194
+ ### 8.2 Compiler warnings
3195
+
3196
+ #### 8.2.1 Use a standard warning set
3197
+
3198
+ As far as possible projects should use
3199
+ `--warning_level=VERBOSE`.
3200
+
3201
+ #### 8.2.2 How to handle a warning
3202
+
3203
+ Before doing anything, make sure you understand exactly what the warning is
3204
+ telling you. If you're not positive why a warning is appearing, ask for help
3205
+ .
3206
+
3207
+ Once you understand the warning, attempt the following solutions in order:
3208
+
3209
+ 1. **First, fix it or work around it.** Make a strong attempt to actually
3210
+ address the warning, or find another way to accomplish the task that avoids
3211
+ the situation entirely.
3212
+ 2. **Otherwise, determine if it's a false alarm.** If you are convinced that
3213
+ the warning is invalid and that the code is actually safe and correct, add a
3214
+ comment to convince the reader of this fact and apply the `@suppress`
3215
+ annotation.
3216
+ 3. **Otherwise, leave a TODO comment.** This is a **last resort**.
3217
+ If you do this, **do
3218
+ not suppress the warning.** The warning should be visible until it can be
3219
+ taken care of properly.
3220
+
3221
+ #### 8.2.3 Suppress a warning at the narrowest reasonable scope
3222
+
3223
+ Warnings are suppressed at the narrowest reasonable scope, usually that of a
3224
+ single local variable or very small method. Often a variable or method is
3225
+ extracted for that reason alone.
3226
+
3227
+ Example
3228
+
3229
+ ```
3230
+ /** @suppress {uselessCode} Unrecognized 'use asm' declaration */
3231
+ function fn() {
3232
+ 'use asm';
3233
+ return 0;
3234
+ }
3235
+ ```
3236
+
3237
+ Even a large number of suppressions in a class is still better than blinding the
3238
+ entire class to this type of warning.
3239
+
3240
+ ### 8.3 Deprecation
3241
+
3242
+ Mark deprecated methods, classes or interfaces with `@deprecated` annotations. A
3243
+ deprecation comment must include simple, clear directions for people to fix
3244
+ their call sites.
3245
+
3246
+ ### 8.4 Code not in Google Style
3247
+
3248
+ You will occasionally encounter files in your codebase that are not in proper
3249
+ Google Style. These may have come from an acquisition, or may have been written
3250
+ before Google Style took a position on some issue, or may be in non-Google Style
3251
+ for any other reason.
3252
+
3253
+ #### 8.4.1 Reformatting existing code
3254
+
3255
+ When updating the style of existing code, follow these guidelines.
3256
+
3257
+ 1. It is not required to change all existing code to meet current style
3258
+ guidelines. Reformatting existing code is a trade-off between code churn and
3259
+ consistency. Style rules evolve over time and these kinds of tweaks to
3260
+ maintain compliance would create unnecessary churn. However, if significant
3261
+ changes are being made to a file it is expected that the file will be in
3262
+ Google Style.
3263
+ 2. Be careful not to allow opportunistic style fixes to muddle the focus of a
3264
+ CL. If you find yourself making a lot of style changes that aren’t critical
3265
+ to the central focus of a CL, promote those changes to a separate CL.
3266
+
3267
+ #### 8.4.2 Newly added code: use Google Style
3268
+
3269
+ Brand new files use Google Style, regardless of the style choices of other files
3270
+ in the same package.
3271
+
3272
+ When adding new code to a file that is not in Google Style, reformatting the
3273
+ existing code first is recommended, subject to the advice in
3274
+ [??](#policies-reformatting-existing-code).
3275
+
3276
+ If this reformatting is not done, then new code should be as consistent as
3277
+ possible with existing code in the same file, but must not violate the style
3278
+ guide.
3279
+
3280
+ ### 8.5 Local style rules
3281
+
3282
+ Teams and projects may adopt additional style rules beyond those in this
3283
+ document, but must accept that cleanup changes may not abide by these additional
3284
+ rules, and must not block such cleanup changes due to violating any additional
3285
+ rules. Beware of excessive rules which serve no purpose. The style guide does
3286
+ not seek to define style in every possible scenario and neither should you.
3287
+
3288
+ ### 8.6 Generated code: mostly exempt
3289
+
3290
+ Source code generated by the build process is not required to be in Google
3291
+ Style. However, any generated identifiers that will be referenced from
3292
+ hand-written source code must follow the naming requirements. As a special
3293
+ exception, such identifiers are allowed to contain underscores, which may help
3294
+ to avoid conflicts with hand-written identifiers.
3295
+
3296
+ ## 9 Appendices
3297
+
3298
+ ### 9.1 JSDoc tag reference
3299
+
3300
+ JSDoc serves multiple purposes in JavaScript. In addition to being used to
3301
+ generate documentation it is also used to control tooling. The best known are
3302
+ the Closure Compiler type annotations.
3303
+
3304
+ #### 9.1.1 Type annotations and other Closure Compiler annotations
3305
+
3306
+ Documentation for JSDoc used by the Closure Compiler is described in
3307
+ [Annotating JavaScript for the Closure Compiler](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler) and
3308
+ [Types in the Closure Type System](https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System).
3309
+
3310
+ #### 9.1.2 Documentation annotations
3311
+
3312
+ In addition to the JSDoc described in
3313
+ [Annotating JavaScript for the Closure Compiler](https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler) the following tags are common
3314
+ and well supported by various documentation generation tools (such as
3315
+ [JsDossier](https://github.com/jleyba/js-dossier)) for purely documentation purposes.
3316
+
3317
+ ##### 9.1.2.1 `@author` or `@owner` - *Not recommended.*
3318
+
3319
+ **Not recommended.**
3320
+
3321
+ Syntax: `@author username@google.com (First Last)`
3322
+
3323
+ ```
3324
+ /**
3325
+ * @fileoverview Utilities for handling textareas.
3326
+ * @author kuth@google.com (Uthur Pendragon)
3327
+ */
3328
+ ```
3329
+
3330
+ Documents the author of a file or the owner of a test, generally only used in
3331
+ the `@fileoverview` comment. The `@owner` tag is used by the unit test dashboard
3332
+ to determine who owns the test results.
3333
+
3334
+ ##### 9.1.2.2 `@bug`
3335
+
3336
+ Syntax: `@bug bugnumber`
3337
+
3338
+ ```
3339
+ /** @bug 1234567 */
3340
+ function testSomething() {
3341
+ // …
3342
+ }
3343
+
3344
+ /**
3345
+ * @bug 1234568
3346
+ * @bug 1234569
3347
+ */
3348
+ function testTwoBugs() {
3349
+ // …
3350
+ }
3351
+ ```
3352
+
3353
+ Indicates what bugs the given test function regression tests.
3354
+
3355
+ Multiple bugs should each have their own `@bug` line, to make searching for
3356
+ regression tests as easy as possible.
3357
+
3358
+ ##### 9.1.2.3 `@code` - *Deprecated. Do not use.*
3359
+
3360
+ **Deprecated. Do not use. Use Markdown backticks instead.**
3361
+
3362
+ Syntax: `{@code ...}`
3363
+
3364
+ Historically, `` `BatchItem` `` was written as
3365
+ `{@code BatchItem}`.
3366
+
3367
+ ```
3368
+ /** Processes pending `BatchItem` instances. */
3369
+ function processBatchItems() {}
3370
+ ```
3371
+
3372
+ Indicates that a term in a JSDoc description is code so it may be correctly
3373
+ formatted in generated documentation.
3374
+
3375
+ ##### 9.1.2.4 `@desc`
3376
+
3377
+ Syntax: `@desc Message description`
3378
+
3379
+ ```
3380
+ /** @desc Notifying a user that their account has been created. */
3381
+ exports.MSG_ACCOUNT_CREATED = goog.getMsg(
3382
+ 'Your account has been successfully created.');
3383
+ ```
3384
+
3385
+ ##### 9.1.2.5 `@link`
3386
+
3387
+ Syntax: `{@link ...}`
3388
+
3389
+ This tag is used to generate cross-reference links within generated
3390
+ documentation.
3391
+
3392
+ ```
3393
+ /** Processes pending {@link BatchItem} instances. */
3394
+ function processBatchItems() {}
3395
+ ```
3396
+
3397
+ **Historical note:** @link tags have also been used to create external links in
3398
+ generated documentation. For external links, always use Markdown's link syntax
3399
+ instead:
3400
+
3401
+ ```
3402
+ /**
3403
+ * This class implements a useful subset of the
3404
+ * [native Event interface](https://dom.spec.whatwg.org/#event).
3405
+ */
3406
+ class ApplicationEvent {}
3407
+ ```
3408
+
3409
+ ##### 9.1.2.6 `@see`
3410
+
3411
+ Syntax: `@see Link`
3412
+
3413
+ ```
3414
+ /**
3415
+ * Adds a single item, recklessly.
3416
+ * @see #addSafely
3417
+ * @see goog.Collect
3418
+ * @see goog.RecklessAdder#add
3419
+ */
3420
+ ```
3421
+
3422
+ Reference a lookup to another class function or method.
3423
+
3424
+ ##### 9.1.2.7 `@supported`
3425
+
3426
+ Syntax: `@supported Description`
3427
+
3428
+ ```
3429
+ /**
3430
+ * @fileoverview Event Manager
3431
+ * Provides an abstracted interface to the browsers' event systems.
3432
+ * @supported IE10+, Chrome, Safari
3433
+ */
3434
+ ```
3435
+
3436
+ Used in a fileoverview to indicate what browsers are supported by the file.
3437
+
3438
+ You may also see other types of JSDoc annotations in third-party code. These
3439
+ annotations appear in the [JSDoc Toolkit Tag Reference](http://code.google.com/p/jsdoc-toolkit/wiki/TagReference) but are not considered
3440
+ part of valid Google style.
3441
+
3442
+ #### 9.1.3 Framework specific annotations
3443
+
3444
+ The following annotations are specific to a particular framework.
3445
+
3446
+ ##### 9.1.3.1 `@ngInject` for Angular 1
3447
+
3448
+ ##### 9.1.3.2 `@polymerBehavior` for Polymer
3449
+
3450
+ <https://github.com/google/closure-compiler/wiki/Polymer-Pass>
3451
+
3452
+ #### 9.1.4 Notes about standard Closure Compiler annotations
3453
+
3454
+ The following tags used to be standard but are now deprecated.
3455
+
3456
+ ##### 9.1.4.1 `@expose` - *Deprecated. Do not use.*
3457
+
3458
+ **Deprecated. Do not use. Use `@export` and/or `@nocollapse` instead.**
3459
+
3460
+ ##### 9.1.4.2 `@inheritDoc` - *Deprecated. Do not use.*
3461
+
3462
+ **Deprecated. Do not use. Use `@override` instead.**
3463
+
3464
+ ### 9.2 Commonly misunderstood style rules
3465
+
3466
+ Here is a collection of lesser-known or commonly misunderstood facts about
3467
+ Google Style for JavaScript. (The following are true statements; this is not a
3468
+ list of "myths.")
3469
+
3470
+ * Neither a copyright statement nor `@author` credit is required in a source
3471
+ file. (Neither is explicitly recommended, either.)
3472
+ * There is no "hard and fast" rule governing how to order the members of a
3473
+ class ([??](#features-classes)).
3474
+ * Empty blocks can usually be represented concisely as `{}`, as detailed in
3475
+ ([??](#formatting-empty-blocks)).
3476
+ * The prime directive of line-wrapping is: prefer to break at a higher
3477
+ syntactic level ([??](#formatting-where-to-break)).
3478
+ * Non-ASCII characters are allowed in string literals, comments and JSDoc, and
3479
+ in fact are recommended when they make the code easier to read than the
3480
+ equivalent Unicode escape would ([??](#non-ascii-characters)).
3481
+
3482
+ ### 9.3 Style-related tools
3483
+
3484
+ The following tools exist to support various aspects of Google Style.
3485
+
3486
+ #### 9.3.1 Closure Compiler
3487
+
3488
+ This program performs type checking and
3489
+ other checks, optimizations and other transformations (such as lowering code to
3490
+ ECMAScript 5).
3491
+
3492
+ #### 9.3.2 `clang-format`
3493
+
3494
+ This program reformats
3495
+ JavaScript source code into Google Style, and also follows a number of
3496
+ non-required but frequently readability-enhancing formatting practices. The
3497
+ output produced by `clang-format` is compliant with the style guide.
3498
+
3499
+ `clang-format` is not required. Authors are allowed to change its output, and
3500
+ reviewers are allowed to ask for such changes; disputes are worked out in the
3501
+ usual way. However, subtrees may choose to opt in to such enforcement locally.
3502
+
3503
+ #### 9.3.3 Closure compiler linter
3504
+
3505
+ This program checks for a
3506
+ variety of missteps and anti-patterns.
3507
+
3508
+ #### 9.3.4 Conformance framework
3509
+
3510
+ The JS Conformance Framework is a tool that is part of the Closure Compiler that
3511
+ provides developers a simple means to specify a set of additional checks to be
3512
+ run against their code base above the standard checks. Conformance checks can,
3513
+ for example, forbid access to a certain property, or calls to a certain
3514
+ function, or missing type information (unknowns).
3515
+
3516
+ These rules are commonly used to enforce critical restrictions (such as defining
3517
+ globals, which could break the codebase) and security patterns (such as using
3518
+ `eval` or assigning to `innerHTML`), or more loosely to improve code quality.
3519
+
3520
+ For additional information see the official documentation for the
3521
+ [JS Conformance Framework](https://github.com/google/closure-compiler/wiki/JS-Conformance-Framework).
3522
+
3523
+ ### 9.4 Exceptions for legacy platforms
3524
+
3525
+ #### 9.4.1 Overview
3526
+
3527
+ This section describes exceptions and additional rules to be followed when
3528
+ modern ECMAScript syntax is not available to the code authors. Exceptions to the
3529
+ recommended style are required when modern ECMAScript syntax is not possible and
3530
+ are outlined here:
3531
+
3532
+ * Use of `var` declarations is allowed
3533
+ * Use of `arguments` is allowed
3534
+ * Optional parameters without default values are allowed
3535
+
3536
+ #### 9.4.2 Use `var`
3537
+
3538
+ ##### 9.4.2.1 `var` declarations are NOT block-scoped
3539
+
3540
+ `var` declarations are scoped to the beginning of the nearest enclosing
3541
+ function, script or module, which can cause unexpected behavior, especially with
3542
+ function closures that reference `var` declarations inside of loops. The
3543
+ following code gives an example:
3544
+
3545
+ ```
3546
+ for (var i = 0; i < 3; ++i) {
3547
+ var iteration = i;
3548
+ setTimeout(function() { console.log(iteration); }, i*1000);
3549
+ }
3550
+
3551
+ // logs 2, 2, 2 -- NOT 0, 1, 2
3552
+ // because `iteration` is function-scoped, not local to the loop.
3553
+ ```
3554
+
3555
+ ##### 9.4.2.2 Declare variables as close as possible to first use
3556
+
3557
+ Even though `var` declarations are scoped to the beginning of the enclosing
3558
+ function, `var` declarations should be as close as possible to their first use,
3559
+ for readability purposes. However, do not put a `var` declaration inside a block
3560
+ if that variable is referenced outside the block. For example:
3561
+
3562
+ ```
3563
+ function sillyFunction() {
3564
+ var count = 0;
3565
+ for (var x in y) {
3566
+ // "count" could be declared here, but don't do that.
3567
+ count++;
3568
+ }
3569
+ console.log(count + ' items in y');
3570
+ }
3571
+ ```
3572
+
3573
+ ##### 9.4.2.3 Use @const for constants variables
3574
+
3575
+ For global declarations where the `const` keyword would be used, if it were
3576
+ available, annotate the `var` declaration with `@const` instead (this is
3577
+ optional for local variables).
3578
+
3579
+ #### 9.4.3 Do not use block scoped functions declarations
3580
+
3581
+ Do **not** do this:
3582
+
3583
+ ```
3584
+ if (x) {
3585
+ function foo() {}
3586
+ }
3587
+ ```
3588
+
3589
+ While most JavaScript VMs implemented before ECMAScript 6 support function
3590
+ declarations within blocks it was not standardized. Implementations were
3591
+ inconsistent with each other and with the now-standard ECMAScript behavior for
3592
+ block scoped function declaration. The ECMAScript 5 standard and prior only
3593
+ allow for function declarations in the root statement list of a script or
3594
+ function and explicitly ban them in block scopes in strict mode.
3595
+
3596
+ To get consistent behavior, instead use a `var` initialized with a function
3597
+ expression to define a function within a block:
3598
+
3599
+ ```
3600
+ if (x) {
3601
+ var foo = function() {};
3602
+ }
3603
+ ```
3604
+
3605
+ #### 9.4.4 Dependency management with `goog.provide`/`goog.require`
3606
+
3607
+ ##### 9.4.4.1 Summary
3608
+
3609
+ **WARNING: `goog.provide` dependency management is deprecated.** All new files,
3610
+ even in projects using `goog.provide` for older files, should use
3611
+ [`goog.module`](#source-file-structure). The following rules are for
3612
+ pre-existing `goog.provide` files only.
3613
+
3614
+ * Place all `goog.provide`s first, `goog.require`s second. Separate provides
3615
+ from requires with an empty line.
3616
+ * Sort the entries alphabetically (uppercase first).
3617
+ * Don't wrap `goog.provide` and `goog.require` statements. Exceed 80 columns
3618
+ if necessary.
3619
+ * Only provide top-level symbols.
3620
+
3621
+ `goog.provide` statements should be grouped together and placed first. All
3622
+ `goog.require` statements should follow. The two lists should be separated with
3623
+ an empty line.
3624
+
3625
+ Similar to import statements in other languages, `goog.provide` and
3626
+ `goog.require` statements should be written in a single line, even if they
3627
+ exceed the 80 column line length limit.
3628
+
3629
+ The lines should be sorted alphabetically, with uppercase letters coming first:
3630
+
3631
+ ```
3632
+ goog.provide('namespace.MyClass');
3633
+ goog.provide('namespace.helperFoo');
3634
+
3635
+ goog.require('an.extremelyLongNamespace.thatSomeoneThought.wouldBeNice.andNowItIsLonger.Than80Columns');
3636
+ goog.require('goog.dom');
3637
+ goog.require('goog.dom.TagName');
3638
+ goog.require('goog.dom.classes');
3639
+ goog.require('goog.dominoes');
3640
+ ```
3641
+
3642
+ All members defined on a class should be in the same file. Only top-level
3643
+ classes should be provided in a file that contains multiple members defined on
3644
+ the same class (e.g. enums, inner classes, etc).
3645
+
3646
+ Do this:
3647
+
3648
+ ```
3649
+ goog.provide('namespace.MyClass');
3650
+ ```
3651
+
3652
+ Not this:
3653
+
3654
+ ```
3655
+ goog.provide('namespace.MyClass');
3656
+ goog.provide('namespace.MyClass.CONSTANT');
3657
+ goog.provide('namespace.MyClass.Enum');
3658
+ goog.provide('namespace.MyClass.InnerClass');
3659
+ goog.provide('namespace.MyClass.TypeDef');
3660
+ goog.provide('namespace.MyClass.staticMethod');
3661
+ ```
3662
+
3663
+ Members on namespaces may also be provided:
3664
+
3665
+ ```
3666
+ goog.provide('foo.bar');
3667
+ goog.provide('foo.bar.CONSTANT');
3668
+ goog.provide('foo.bar.method');
3669
+ ```
3670
+
3671
+ ##### 9.4.4.2 Aliasing with `goog.scope`
3672
+
3673
+ **WARNING: `goog.scope` is deprecated.** New files should not use `goog.scope`
3674
+ even in projects with existing `goog.scope` usage.
3675
+
3676
+ `goog.scope` may be used to shorten references to namespaced symbols in code
3677
+ using `goog.provide`/`goog.require` dependency management.
3678
+
3679
+ Only one `goog.scope` invocation may be added per file. Always place it in the
3680
+ global scope.
3681
+
3682
+ The opening `goog.scope(function() {` invocation must be preceded by exactly one
3683
+ blank line and follow any `goog.provide` statements, `goog.require` statements,
3684
+ or top-level comments. The invocation must be closed on the last line in the
3685
+ file. Append `// goog.scope` to the closing statement of the scope. Separate the
3686
+ comment from the semicolon by two spaces.
3687
+
3688
+ Similar to C++ namespaces, do not indent under `goog.scope` declarations.
3689
+ Instead, continue from the 0 column.
3690
+
3691
+ Only make aliases for names that will not be re-assigned to another object
3692
+ (e.g., most constructors, enums, and namespaces). Do not do this (see below for
3693
+ how to alias a constructor):
3694
+
3695
+ ```
3696
+ goog.scope(function() {
3697
+ var Button = goog.ui.Button;
3698
+
3699
+ Button = function() { ... };
3700
+ ...
3701
+ ```
3702
+
3703
+ Names must be the same as the last property of the global that they are
3704
+ aliasing.
3705
+
3706
+ ```
3707
+ goog.provide('my.module.SomeType');
3708
+
3709
+ goog.require('goog.dom');
3710
+ goog.require('goog.ui.Button');
3711
+
3712
+ goog.scope(function() {
3713
+ var Button = goog.ui.Button;
3714
+ var dom = goog.dom;
3715
+
3716
+ // Alias new types after the constructor declaration.
3717
+ my.module.SomeType = function() { ... };
3718
+ var SomeType = my.module.SomeType;
3719
+
3720
+ // Declare methods on the prototype as usual:
3721
+ SomeType.prototype.findButton = function() {
3722
+ // Button as aliased above.
3723
+ this.button = new Button(dom.getElement('my-button'));
3724
+ };
3725
+ ...
3726
+ }); // goog.scope
3727
+ ```
3728
+
3729
+ ##### 9.4.4.3 `goog.forwardDeclare`
3730
+
3731
+ Prefer to use `goog.requireType` instead of `goog.forwardDeclare` to break
3732
+ circular dependencies between files in the same library. Unlike `goog.require`,
3733
+ a `goog.requireType` statement is allowed to import a namespace before it is
3734
+ defined.
3735
+
3736
+ `goog.forwardDeclare` statements must follow the same style rules as
3737
+ `goog.require` and `goog.requireType`. The entire block of
3738
+ `goog.forwardDeclare`, `goog.require` and `goog.requireType` statements is
3739
+ sorted alphabetically.
3740
+
3741
+ `goog.forwardDeclare` is used in legacy code to break circular references
3742
+ spanning *across library boundaries*. This pattern however is poorly supported
3743
+ by build tools and should not be used. Code should be organized to avoid
3744
+ circular dependencies across libraries (by splitting/merging libraries).
3745
+
3746
+ ##### 9.4.4.4 `goog.module.get(name)`
3747
+
3748
+ If a `goog.provide` file depends on a `goog.module` file, the `goog.provide`
3749
+ file can not normally refer to the module's exports via a global name. Instead,
3750
+ in addition to `goog.require()`ing the module, the `goog.provide` file must
3751
+ fetch the module's export object by calling `goog.module.get('module.name')`.
3752
+
3753
+ Note: Only calling `goog.module.get('module.name')` does not create a build-time
3754
+ dependency of your code on the module. The `goog.require` is needed for the
3755
+ build dependency.
3756
+
3757
+ ##### 9.4.4.5 `goog.module.declareLegacyNamespace()`
3758
+
3759
+ **WARNING: `goog.module.declareLegacyNamespace` is only for transitional use.**
3760
+
3761
+ `goog.module.declareLegacyNamespace` is only for use while migrating a
3762
+ JavaScript file and its consumers from `goog.provide` to `goog.module`
3763
+ . Update consumers of
3764
+ your [`goog.module`](#source-file-structure) to use `goog.module` themselves.
3765
+ Remove calls to `goog.module.declareLegacyNamespace` whenever possible.
3766
+
3767
+ If you can't update consumers of a legacy namespace from `goog.provide` to
3768
+ `goog.module` soon, please wrap the contents of your file in a call to
3769
+ `goog.scope`, use `goog.module.get` to import the legacy namespace--and then
3770
+ delete the call to `goog.module.declareLegacyNamespace` in your `goog.module`.
3771
+
3772
+ Calling `goog.module.declareLegacyNamespace()` inside a `goog.module(name)` will
3773
+ declare the module's namespace as a global name just like a `goog.provide()`
3774
+ call does. This allows a non `goog.module` namespace to access the module's
3775
+ exports without calling `goog.module.get(name)`.