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