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’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 “JSDoc” 34for both human-readable text and machine-readable annotations within 35<code>/** … */</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’ 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>∞</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<table> 93 <thead> 94 <tr> 95 <th>Example 96 </th><th>Discussion 97 </th></tr></thead><tbody> 98 <tr> 99 <td><code class="prettyprint lang-js">const units = 'μs';</code> 100 </td><td>Best: perfectly clear even without a comment. 101 </td></tr><tr> 102 <td> 103 <code class="prettyprint lang-js">const units = '\u03bcs'; // 'μs' 104 </code> 105 </td><td>Allowed, but there’s no reason to do this. 106 </td></tr><tr> 107 <td> 108 <code class="prettyprint lang-js">const units = '\u03bcs'; // Greek letter mu, 's' 109 </code> 110 </td><td>Allowed, but awkward and prone to mistakes. 111 </td></tr><tr> 112 <td><code class="badcode">const units = '\u03bcs';</code> 113 </td><td>Poor: the reader has no idea what this is. 114 </td></tr><tr> 115 <td> 116 <code class="prettyprint lang-js">return '\ufeff' + content; // byte order mark 117 </code> 118 </td><td> 119 Good: use escapes for non-printable characters, and comment if 120 necessary. 121</td></tr></tbody></table> 122 123<p>Tip: Never make your code less readable simply out of fear that some programs 124might not handle non-ASCII characters properly. If that happens, those programs 125are <strong>broken</strong> and they must be <strong>fixed</strong>.</p> 126 127<h2 id="source-file-structure">3 Source file structure</h2> 128 129<p>A source file consists of, <strong>in order</strong>:</p> 130 131<ol> 132<li>License or copyright information, if present</li> 133<li><code>@fileoverview</code> JSDoc, if present</li> 134<li><code>goog.module</code> statement</li> 135<li><code>goog.require</code> statements</li> 136<li>The file’s implementation</li> 137</ol> 138 139<p><strong>Exactly one blank line</strong> separates each section that is present, except the 140file's implementation, which may be preceded by 1 or 2 blank lines.</p> 141 142<h3 id="file-copyright">3.1 License or copyright information, if present</h3> 143 144<p>If license or copyright information belongs in a file, it belongs here.</p> 145 146<h3 id="file-fileoverview">3.2 <code>@fileoverview</code> JSDoc, if present</h3> 147 148<p>See <a href="#jsdoc-top-file-level-comments">??</a> for formatting rules.</p> 149 150<h3 id="file-goog-module">3.3 <code>goog.module</code> statement</h3> 151 152<p>All files must declare exactly one <code>goog.module</code> name on a single line: lines 153containing a <code>goog.module</code> declaration must not be wrapped, and are therefore an 154exception to the 80-column limit.</p> 155 156<p>The entire argument to goog.module is what defines a namespace. It is the 157package name (an identifier that reflects the fragment of the directory 158structure where the code lives) plus, optionally, the main class/enum/interface 159that it defines concatenated to the end.</p> 160 161<p>Example</p> 162 163<pre><code class="language-js prettyprint">goog.module('search.urlHistory.UrlHistoryService'); 164</code></pre> 165 166<h4 id="naming-hierarchy">3.3.1 Hierarchy</h4> 167 168<p>Module namespaces may never be named as a <em>direct</em> child of another module's 169namespace.</p> 170 171<p>Illegal:</p> 172 173<pre><code class="language-js prettyprint badcode">goog.module('foo.bar'); // 'foo.bar.qux' would be fine, though 174goog.module('foo.bar.baz'); 175</code></pre> 176 177<p>The directory hierarchy reflects the namespace hierarchy, so that deeper-nested 178children are subdirectories of higher-level parent directories. Note that this 179implies that owners of “parent” namespace groups are necessarily aware of all 180child namespaces, since they exist in the same directory.</p> 181 182<h4 id="file-set-test-only">3.3.2 <code>goog.setTestOnly</code></h4> 183 184<p>The single <code>goog.module</code> statement may optionally be followed by a call to 185goog.setTestOnly().</p> 186 187<h4 id="file-declare-legacy-namespace">3.3.3 <code>goog.module.declareLegacyNamespace</code></h4> 188 189<p>The single <code>goog.module</code> statement may optionally be followed by a call to 190<code>goog.module.declareLegacyNamespace();</code>. Avoid 191<code>goog.module.declareLegacyNamespace()</code> when possible.</p> 192 193<p>Example:</p> 194 195<pre><code class="language-js prettyprint">goog.module('my.test.helpers'); 196goog.module.declareLegacyNamespace(); 197goog.setTestOnly(); 198</code></pre> 199 200<p><code>goog.module.declareLegacyNamespace</code> exists to ease the transition from 201traditional object hierarchy-based namespaces but comes with some naming 202restrictions. As the child module name must be created after the parent 203namespace, this name <strong>must not</strong> be a child or parent of any other 204<code>goog.module</code> (for example, <code>goog.module('parent');</code> and 205<code>goog.module('parent.child');</code> cannot both exist safely, nor can 206<code>goog.module('parent');</code> and <code>goog.module('parent.child.grandchild');</code>).</p> 207 208<h4 id="file-es6-modules">3.3.4 ES6 Modules</h4> 209 210<p>Do not use ES6 modules yet (i.e. the <code>export</code> and <code>import</code> keywords), as their 211semantics are not yet finalized. Note that this policy will be revisited once 212the semantics are fully-standard.</p> 213 214<h3 id="file-goog-require">3.4 <code>goog.require</code> statements</h3> 215 216<p>Imports are done with <code>goog.require</code> statements, grouped together immediately 217following the module declaration. Each <code>goog.require</code> is assigned to a single 218constant alias, or else destructured into several constant aliases. These 219aliases are the only acceptable way to refer to the <code>require</code>d dependency, 220whether in code or in type annotations: the fully qualified name is never used 221except as the argument to <code>goog.require</code>. Alias names should match the final 222dot-separated component of the imported module name when possible, though 223additional components may be included (with appropriate casing such that the 224alias' casing still correctly identifies its type) if necessary to 225disambiguate, or if it significantly improves readability. <code>goog.require</code> 226statements may not appear anywhere else in the file.</p> 227 228<p>If a module is imported only for its side effects, the assignment may be 229omitted, but the fully qualified name may not appear anywhere else in the file. 230A comment is required to explain why this is needed and suppress a compiler 231warning.</p> 232 233 234 235<p>The lines are sorted according to the following rules: All requires with a name 236on the left hand side come first, sorted alphabetically by those names. Then 237destructuring requires, again sorted by the names on the left hand side. 238Finally, any <code>goog.require</code> calls that are standalone (generally these are for 239modules imported just for their side effects).</p> 240 241<p>Tip: There’s no need to memorize this order and enforce it manually. You can 242rely on your IDE to report requires 243that are not sorted correctly.</p> 244 245<p>If a long alias or module name would cause a line to exceed the 80-column limit, 246it <strong>must not</strong> be wrapped: goog.require lines are an exception to the 80-column 247limit.</p> 248 249<p>Example:</p> 250 251<pre><code class="language-js prettyprint">const MyClass = goog.require('some.package.MyClass'); 252const NsMyClass = goog.require('other.ns.MyClass'); 253const googAsserts = goog.require('goog.asserts'); 254const testingAsserts = goog.require('goog.testing.asserts'); 255const than80columns = goog.require('pretend.this.is.longer.than80columns'); 256const {clear, forEach, map} = goog.require('goog.array'); 257/** @suppress {extraRequire} Initializes MyFramework. */ 258goog.require('my.framework.initialization'); 259</code></pre> 260 261<p>Illegal:</p> 262 263<pre><code class="language-js badcode prettyprint">const randomName = goog.require('something.else'); // name must match 264 265const {clear, forEach, map} = // don't break lines 266 goog.require('goog.array'); 267 268function someFunction() { 269 const alias = goog.require('my.long.name.alias'); // must be at top level 270 // … 271} 272</code></pre> 273 274<h4 id="file-goog-forward-declare">3.4.1 <code>goog.forwardDeclare</code></h4> 275 276<p><code>goog.forwardDeclare</code> is not needed very often, but is a valuable tool to break 277circular dependencies or to reference late loaded code. These statements are 278grouped together and immediately follow any <code>goog.require</code> statements. A 279<code>goog.forwardDeclare</code> statement must follow the same style rules as a 280<code>goog.require</code> statement.</p> 281 282<h3 id="file-implementation">3.5 The file’s implementation</h3> 283 284<p>The actual implementation follows after all dependency information is declared 285(separated by at least one blank line).</p> 286 287<p>This may consist of any module-local declarations (constants, variables, 288classes, functions, etc), as well as any exported symbols. 289</p> 290 291<h2 id="formatting">4 Formatting</h2> 292 293<p><strong>Terminology Note</strong>: <em>block-like construct</em> refers to the body of a class, 294function, method, or brace-delimited block of code. Note that, by 295<a href="#features-array-literals">??</a> and <a href="#features-object-literals">??</a>, any array or 296object literal may optionally be treated as if it were a block-like construct.</p> 297 298<p>Tip: Use <code>clang-format</code>. The JavaScript community has invested effort to make 299sure clang-format <q>does the right thing</q> on JavaScript files. <code>clang-format</code> has 300integration with several popular 301editors.</p> 302 303<h3 id="formatting-braces">4.1 Braces</h3> 304 305<h4 id="formatting-braces-all">4.1.1 Braces are used for all control structures</h4> 306 307<p>Braces are required for all control structures (i.e. <code>if</code>, <code>else</code>, <code>for</code>, <code>do</code>, 308<code>while</code>, as well as any others), even if the body contains only a single 309statement. The first statement of a non-empty block must begin on its own line.</p> 310 311<p>Illegal:</p> 312 313<pre><code class="language-js badcode prettyprint">if (someVeryLongCondition()) 314 doSomething(); 315 316for (let i = 0; i < foo.length; i++) bar(foo[i]); 317</code></pre> 318 319<p><strong>Exception</strong>: A simple if statement that can fit entirely on a single line with 320no wrapping (and that doesn’t have an else) may be kept on a single line with no 321braces when it improves readability. This is the only case in which a control 322structure may omit braces and newlines.</p> 323 324<pre><code class="language-js prettyprint">if (shortCondition()) return; 325</code></pre> 326 327<h4 id="formatting-nonempty-blocks">4.1.2 Nonempty blocks: K&R style</h4> 328 329<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 330<em>nonempty</em> blocks and block-like constructs:</p> 331 332<ul> 333<li>No line break before the opening brace.</li> 334<li>Line break after the opening brace.</li> 335<li>Line break before the closing brace.</li> 336<li>Line break after the closing brace <em>if</em> that brace terminates a statement or 337the body of a function or class statement, or a class method. Specifically, 338there is <em>no</em> line break after the brace if it is followed by <code>else</code>, <code>catch</code>, 339<code>while</code>, or a comma, semicolon, or right-parenthesis.</li> 340</ul> 341 342<p>Example:</p> 343 344<pre><code class="language-js prettyprint">class InnerClass { 345 constructor() {} 346 347 /** @param {number} foo */ 348 method(foo) { 349 if (condition(foo)) { 350 try { 351 // Note: this might fail. 352 something(); 353 } catch (err) { 354 recover(); 355 } 356 } 357 } 358} 359</code></pre> 360 361<h4 id="formatting-empty-blocks">4.1.3 Empty blocks: may be concise</h4> 362 363<p>An empty block or block-like construct <em>may</em> be closed immediately after it is 364opened, with no characters, space, or line break in between (i.e. <code>{}</code>), 365<strong>unless</strong> it is a part of a <em>multi-block statement</em> (one that directly contains 366multiple blocks: <code>if</code>/<code>else</code> or <code>try</code>/<code>catch</code>/<code>finally</code>).</p> 367 368<p>Example:</p> 369 370<pre><code class="language-js prettyprint">function doNothing() {} 371</code></pre> 372 373<p>Illegal:</p> 374 375<pre><code class="language-js prettyprint badcode">if (condition) { 376 // … 377} else if (otherCondition) {} else { 378 // … 379} 380 381try { 382 // … 383} catch (e) {} 384</code></pre> 385 386<h3 id="formatting-block-indentation">4.2 Block indentation: +2 spaces</h3> 387 388<p>Each time a new block or block-like construct is opened, the indent increases by 389two spaces. When the block ends, the indent returns to the previous indent 390level. The indent level applies to both code and comments throughout the 391block. (See the example in <a href="#formatting-nonempty-blocks">??</a>).</p> 392 393<h4 id="formatting-array-literals">4.2.1 Array literals: optionally <q>block-like</q></h4> 394 395<p>Any array literal may optionally be formatted as if it were a “block-like 396construct.” For example, the following are all valid (<strong>not</strong> an exhaustive 397list):</p> 398 399<pre><code class="language-js prettyprint columns">const a = [ 400 0, 401 1, 402 2, 403]; 404 405const b = 406 [0, 1, 2]; 407 408</code></pre> 409 410<pre><code class="language-js prettyprint columns">const c = [0, 1, 2]; 411 412someMethod(foo, [ 413 0, 1, 2, 414], bar); 415</code></pre> 416 417<p>Other combinations are allowed, particularly when emphasizing semantic groupings 418between elements, but should not be used only to reduce the vertical size of 419larger arrays.</p> 420 421<h4 id="formatting-object-literals">4.2.2 Object literals: optionally <q>block-like</q></h4> 422 423<p>Any object literal may optionally be formatted as if it were a “block-like 424construct.” The same examples apply as <a href="#formatting-array-literals">??</a>. For 425example, the following are all valid (<strong>not</strong> an exhaustive list):</p> 426 427<pre><code class="language-js prettyprint columns">const a = { 428 a: 0, 429 b: 1, 430}; 431 432const b = 433 {a: 0, b: 1}; 434</code></pre> 435 436<pre><code class="language-js prettyprint columns">const c = {a: 0, b: 1}; 437 438someMethod(foo, { 439 a: 0, b: 1, 440}, bar); 441</code></pre> 442 443<h4 id="formatting-class-literals">4.2.3 Class literals</h4> 444 445<p>Class literals (whether declarations or expressions) are indented as blocks. Do 446not add semicolons after methods, or after the closing brace of a class 447<em>declaration</em> (statements—such as assignments—that contain class <em>expressions</em> 448are still terminated with a semicolon). Use the <code>extends</code> keyword, but not the 449<code>@extends</code> JSDoc annotation unless the class extends a templatized type.</p> 450 451<p>Example:</p> 452 453<pre><code class="language-js prettyprint columns">class Foo { 454 constructor() { 455 /** @type {number} */ 456 this.x = 42; 457 } 458 459 /** @return {number} */ 460 method() { 461 return this.x; 462 } 463} 464Foo.Empty = class {}; 465</code></pre> 466 467<pre><code class="language-js prettyprint columns">/** @extends {Foo<string>} */ 468foo.Bar = class extends Foo { 469 /** @override */ 470 method() { 471 return super.method() / 2; 472 } 473}; 474 475/** @interface */ 476class Frobnicator { 477 /** @param {string} message */ 478 frobnicate(message) {} 479} 480</code></pre> 481 482<h4 id="formatting-function-expressions">4.2.4 Function expressions</h4> 483 484<p>When declaring an anonymous function in the list of arguments for a function 485call, the body of the function is indented two spaces more than the preceding 486indentation depth.</p> 487 488<p>Example:</p> 489 490<pre><code class="language-js prettyprint">prefix.something.reallyLongFunctionName('whatever', (a1, a2) => { 491 // Indent the function body +2 relative to indentation depth 492 // of the 'prefix' statement one line above. 493 if (a1.equals(a2)) { 494 someOtherLongFunctionName(a1); 495 } else { 496 andNowForSomethingCompletelyDifferent(a2.parrot); 497 } 498}); 499 500some.reallyLongFunctionCall(arg1, arg2, arg3) 501 .thatsWrapped() 502 .then((result) => { 503 // Indent the function body +2 relative to the indentation depth 504 // of the '.then()' call. 505 if (result) { 506 result.use(); 507 } 508 }); 509</code></pre> 510 511<h4 id="formatting-switch-statements">4.2.5 Switch statements</h4> 512 513<p>As with any other block, the contents of a switch block are indented +2.</p> 514 515 516 517<p>After a switch label, a newline appears, and the indentation level is increased 518+2, exactly as if a block were being opened. An explicit block may be used if 519required by lexical scoping. The following switch label returns to the previous 520indentation level, as if a block had been closed.</p> 521 522<p>A blank line is optional between a <code>break</code> and the following case.</p> 523 524<p>Example:</p> 525 526<pre><code class="language-js prettyprint">switch (animal) { 527 case Animal.BANDERSNATCH: 528 handleBandersnatch(); 529 break; 530 531 case Animal.JABBERWOCK: 532 handleJabberwock(); 533 break; 534 535 default: 536 throw new Error('Unknown animal'); 537} 538</code></pre> 539 540<h3 id="formatting-statements">4.3 Statements</h3> 541 542<h4 id="formatting-one-statement-perline">4.3.1 One statement per line</h4> 543 544<p>Each statement is followed by a line-break.</p> 545 546<h4 id="formatting-semicolons-are-required">4.3.2 Semicolons are required</h4> 547 548<p>Every statement must be terminated with a semicolon. Relying on automatic 549semicolon insertion is forbidden.</p> 550 551<h3 id="formatting-column-limit">4.4 Column limit: 80</h3> 552 553<p>JavaScript code has a column limit of 80 characters. Except as noted below, any 554line that would exceed this limit must be line-wrapped, as explained in 555<a href="#formatting-line-wrapping">??</a>.</p> 556 557<p><strong>Exceptions:</strong></p> 558 559<ol> 560<li>Lines where obeying the column limit is not possible (for example, a long URL 561in JSDoc or a shell command intended to be copied-and-pasted).</li> 562<li><code>goog.module</code> and <code>goog.require</code> statements (see <a href="#file-goog-module">??</a> and 563<a href="#file-goog-require">??</a>).</li> 564</ol> 565 566<h3 id="formatting-line-wrapping">4.5 Line-wrapping</h3> 567 568<p><strong>Terminology Note</strong>: <em>Line-wrapping</em> is defined as breaking a single expression 569into multiple lines.</p> 570 571<p>There is no comprehensive, deterministic formula showing <em>exactly</em> how to 572line-wrap in every situation. Very often there are several valid ways to 573line-wrap the same piece of code.</p> 574 575<p>Note: While the typical reason for line-wrapping is to avoid overflowing the 576column limit, even code that would in fact fit within the column limit may be 577line-wrapped at the author's discretion.</p> 578 579<p>Tip: Extracting a method or local variable may solve the problem without the 580need to line-wrap.</p> 581 582<h4 id="formatting-where-to-break">4.5.1 Where to break</h4> 583 584<p>The prime directive of line-wrapping is: prefer to break at a <strong>higher syntactic 585level</strong>. </p> 586 587<p>Preferred:</p> 588 589<pre><code class="language-js prettyprint">currentEstimate = 590 calc(currentEstimate + x * currentEstimate) / 591 2.0f; 592</code></pre> 593 594<p>Discouraged:</p> 595 596<pre><code class="language-js prettyprint badcode">currentEstimate = calc(currentEstimate + x * 597 currentEstimate) / 2.0f; 598</code></pre> 599 600<p>In the preceding example, the syntactic levels from highest to lowest are as 601follows: assignment, division, function call, parameters, number constant.</p> 602 603<p>Operators are wrapped as follows:</p> 604 605<ol> 606<li>When a line is broken at an operator the break comes after the symbol. (Note 607that this is not the same practice used in Google style for Java.) 608<ol> 609<li>This does not apply to the <q>dot</q> (<code>.</code>), which is not actually an 610operator.</li> 611</ol></li> 612<li>A method or constructor name stays attached to the open parenthesis (<code>(</code>) 613that follows it.</li> 614<li>A comma (<code>,</code>) stays attached to the token that precedes it.</li> 615</ol> 616 617<blockquote> 618<p>Note: The primary goal for line wrapping is to have clear code, not 619necessarily code that fits in the smallest number of lines.</p> 620</blockquote> 621 622<h4 id="formatting-indent">4.5.2 Indent continuation lines at least +4 spaces</h4> 623 624<p>When line-wrapping, each line after the first (each <em>continuation line</em>) is 625indented at least +4 from the original line, unless it falls under the rules of 626block indentation.</p> 627 628<p>When there are multiple continuation lines, indentation may be varied beyond +4 629as appropriate. In general, continuation lines at a deeper syntactic level are 630indented by larger multiples of 4, and two lines use the same indentation level 631if and only if they begin with syntactically parallel elements.</p> 632 633<p><a href="#formatting-horizontal-alignment">??</a> addresses the discouraged practice of 634using a variable number of spaces to align certain tokens with previous lines.</p> 635 636<h3 id="formatting-whitespace">4.6 Whitespace</h3> 637 638<h4 id="formatting-vertical-whitespace">4.6.1 Vertical whitespace</h4> 639 640<p>A single blank line appears:</p> 641 642<ol> 643<li>Between consecutive methods in a class or object literal 644<ol> 645<li>Exception: A blank line between two consecutive properties definitions in 646an object literal (with no other code between them) is optional. Such 647blank lines are used as needed to create <em>logical groupings</em> of fields.</li> 648</ol></li> 649<li>Within method bodies, sparingly to create <em>logical groupings</em> of statements. 650Blank lines at the start or end of a function body are not allowed.</li> 651<li><em>Optionally</em> before the first or after the last method in a class or object 652literal (neither encouraged nor discouraged).</li> 653<li>As required by other sections of this document (e.g. 654<a href="#file-goog-require">??</a>).</li> 655</ol> 656 657<p><em>Multiple</em> consecutive blank lines are permitted, but never required (nor 658encouraged).</p> 659 660<h4 id="formatting-horizontal-whitespace">4.6.2 Horizontal whitespace</h4> 661 662<p>Use of horizontal whitespace depends on location, and falls into three broad 663categories: <em>leading</em> (at the start of a line), <em>trailing</em> (at the end of a 664line), and <em>internal</em>. Leading whitespace (i.e., indentation) is addressed 665elsewhere. Trailing whitespace is forbidden.</p> 666 667<p>Beyond where required by the language or other style rules, and apart from 668literals, comments, and JSDoc, a single internal ASCII space also appears in the 669following places <strong>only</strong>.</p> 670 671<ol> 672<li>Separating any reserved word (such as <code>if</code>, <code>for</code>, or <code>catch</code>) from an open 673parenthesis (<code>(</code>) that follows it on that line.</li> 674<li>Separating any reserved word (such as <code>else</code> or <code>catch</code>) from a closing 675curly brace (<code>}</code>) that precedes it on that line.</li> 676<li>Before any open curly brace (<code>{</code>), with two exceptions: 677<ol> 678<li>Before an object literal that is the first argument of a function or the 679first element in an array literal (e.g. <code>foo({a: [{c: d}]})</code>).</li> 680<li>In a template expansion, as it is forbidden by the language 681(e.g. <code>abc${1 + 2}def</code>).</li> 682</ol></li> 683<li>On both sides of any binary or ternary operator.</li> 684<li>After a comma (<code>,</code>) or semicolon (<code>;</code>). Note that spaces are <em>never</em> allowed 685before these characters.</li> 686<li>After the colon (<code>:</code>) in an object literal.</li> 687<li>On both sides of the double slash (<code>//</code>) that begins an end-of-line 688comment. Here, multiple spaces are allowed, but not required.</li> 689<li>After an open-JSDoc comment character and on both sides of close characters 690(e.g. for short-form type declarations or casts: <code>this.foo = /** @type 691{number} */ (bar);</code> or <code>function(/** string */ foo) {</code>).</li> 692</ol> 693 694<h4 id="formatting-horizontal-alignment">4.6.3 Horizontal alignment: discouraged</h4> 695 696<p><strong>Terminology Note</strong>: <em>Horizontal alignment</em> is the practice of adding a 697variable number of additional spaces in your code with the goal of making 698certain tokens appear directly below certain other tokens on previous lines.</p> 699 700<p>This practice is permitted, but it is <strong>generally discouraged</strong> by Google 701Style. It is not even required to <em>maintain</em> horizontal alignment in places 702where it was already used.</p> 703 704<p>Here is an example without alignment, followed by one with alignment. Both are 705allowed, but the latter is discouraged:</p> 706 707<pre><code class="language-js prettyprint">{ 708 tiny: 42, // this is great 709 longer: 435, // this too 710}; 711 712{ 713 tiny: 42, // permitted, but future edits 714 longer: 435, // may leave it unaligned 715}; 716</code></pre> 717 718<p>Tip: Alignment can aid readability, but it creates problems for future 719maintenance. Consider a future change that needs to touch just one line. This 720change may leave the formerly-pleasing formatting mangled, and that is 721allowed. More often it prompts the coder (perhaps you) to adjust whitespace on 722nearby lines as well, possibly triggering a cascading series of 723reformattings. That one-line change now has a <q>blast radius.</q> This can at worst 724result in pointless busywork, but at best it still corrupts version history 725information, slows down reviewers and exacerbates merge conflicts.</p> 726 727<h4 id="formatting-function-arguments">4.6.4 Function arguments</h4> 728 729<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> 730 731<pre><code class="language-js prettyprint">// Arguments start on a new line, indented four spaces. Preferred when the 732// arguments don't fit on the same line with the function name (or the keyword 733// "function") but fit entirely on the second line. Works with very long 734// function names, survives renaming without reindenting, low on space. 735doSomething( 736 descriptiveArgumentOne, descriptiveArgumentTwo, descriptiveArgumentThree) { 737 // … 738} 739 740// If the argument list is longer, wrap at 80. Uses less vertical space, 741// but violates the rectangle rule and is thus not recommended. 742doSomething(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo, 743 tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) { 744 // … 745} 746 747// Four-space, one argument per line. Works with long function names, 748// survives renaming, and emphasizes each argument. 749doSomething( 750 veryDescriptiveArgumentNumberOne, 751 veryDescriptiveArgumentTwo, 752 tableModelEventHandlerProxy, 753 artichokeDescriptorAdapterIterator) { 754 // … 755} 756</code></pre> 757 758<h3 id="formatting-grouping-parentheses">4.7 Grouping parentheses: recommended</h3> 759 760<p>Optional grouping parentheses are omitted only when the author and reviewer 761agree that there is no reasonable chance that the code will be misinterpreted 762without them, nor would they have made the code easier to read. It is <em>not</em> 763reasonable to assume that every reader has the entire operator precedence table 764memorized.</p> 765 766<p>Do not use unnecessary parentheses around the entire expression following 767<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> 768 769<p>Parentheses are required for type casts: <code>/** @type {!Foo} */ (foo)</code>.</p> 770 771<h3 id="formatting-comments">4.8 Comments</h3> 772 773<p>This section addresses <em>implementation comments</em>. JSDoc is addressed separately 774in <a href="#jsdoc">??</a>.</p> 775 776<h4 id="formatting-block-comment-style">4.8.1 Block comment style</h4> 777 778<p>Block comments are indented at the same level as the surrounding code. They may 779be in <code>/* … */</code> or <code>//</code>-style. For multi-line <code>/* … */</code> comments, subsequent 780lines must start with * aligned with the <code>*</code> on the previous line, to make 781comments obvious with no extra context. “Parameter name” comments should appear 782after values whenever the value and method name do not sufficiently convey the 783meaning.</p> 784 785<pre><code class="language-js prettyprint">/* 786 * This is 787 * okay. 788 */ 789 790// And so 791// is this. 792 793/* This is fine, too. */ 794 795someFunction(obviousParam, true /* shouldRender */, 'hello' /* name */); 796</code></pre> 797 798<p>Comments are not enclosed in boxes drawn with asterisks or other characters.</p> 799 800<p>Do not use JSDoc (<code>/** … */</code>) for any of the above implementation comments.</p> 801 802<h2 id="language-features">5 Language features</h2> 803 804<p>JavaScript includes many dubious (and even dangerous) features. This section 805delineates which features may or may not be used, and any additional constraints 806on their use.</p> 807 808<h3 id="features-local-variable-declarations">5.1 Local variable declarations</h3> 809 810<h4 id="features-use-const-and-let">5.1.1 Use <code>const</code> and <code>let</code></h4> 811 812<p>Declare all local variables with either <code>const</code> or <code>let</code>. Use const by default, 813unless a variable needs to be reassigned. The <code class="badcode">var</code> 814keyword must not be used.</p> 815 816<h4 id="features-one-variable-per-declaration">5.1.2 One variable per declaration</h4> 817 818<p>Every local variable declaration declares only one variable: declarations such 819as <code class="badcode">let a = 1, b = 2;</code> are not used.</p> 820 821<h4 id="features-declared-when-needed">5.1.3 Declared when needed, initialized as soon as possible</h4> 822 823<p>Local variables are <strong>not</strong> habitually declared at the start of their containing 824block or block-like construct. Instead, local variables are declared close to 825the point they are first used (within reason), to minimize their scope.</p> 826 827<h4 id="features-declare-types-as-needed">5.1.4 Declare types as needed</h4> 828 829<p>JSDoc type annotations may be added either on the line above the declaration, or 830else inline before the variable name.</p> 831 832<p>Example:</p> 833 834<pre><code class="language-js prettyprint">const /** !Array<number> */ data = []; 835 836/** @type {!Array<number>} */ 837const data = []; 838</code></pre> 839 840<p>Tip: There are many cases where the compiler can infer a templatized type but 841not its parameters. This is particularly the case when the initializing literal 842or constructor call does not include any values of the template parameter type 843(e.g., empty arrays, objects, <code>Map</code>s, or <code>Set</code>s), or if the variable is modified 844in a closure. Local variable type annotations are particularly helpful in these 845cases since otherwise the compiler will infer the template parameter as unknown.</p> 846 847<h3 id="features-array-literals">5.2 Array literals</h3> 848 849<h4 id="features-arrays-trailing-comma">5.2.1 Use trailing commas</h4> 850 851 852 853<p>Include a trailing comma whenever there is a line break between the final 854element and the closing bracket.</p> 855 856<p>Example:</p> 857 858<pre><code class="language-js prettyprint">const values = [ 859 'first value', 860 'second value', 861]; 862</code></pre> 863 864<h4 id="features-arrays-ctor">5.2.2 Do not use the variadic <code>Array</code> constructor</h4> 865 866<p>The constructor is error-prone if arguments are added or removed. Use a literal 867instead.</p> 868 869<p>Illegal:</p> 870 871<pre><code class="language-js prettyprint badcode">const a1 = new Array(x1, x2, x3); 872const a2 = new Array(x1, x2); 873const a3 = new Array(x1); 874const a4 = new Array(); 875</code></pre> 876 877<p>This works as expected except for the third case: if <code>x1</code> is a whole number then 878<code>a3</code> is an array of size <code>x1</code> where all elements are <code>undefined</code>. If <code>x1</code> is any 879other number, then an exception will be thrown, and if it is anything else then 880it will be a single-element array.</p> 881 882<p>Instead, write</p> 883 884<pre><code class="language-js prettyprint">const a1 = [x1, x2, x3]; 885const a2 = [x1, x2]; 886const a3 = [x1]; 887const a4 = []; 888</code></pre> 889 890<p>Explicitly allocating an array of a given length using <code>new Array(length)</code> is 891allowed when appropriate.</p> 892 893<h4 id="features-arrays-non-numeric-properties">5.2.3 Non-numeric properties</h4> 894 895<p>Do not define or use non-numeric properties on an array (other than 896<code>length</code>). Use a <code>Map</code> (or <code>Object</code>) instead.</p> 897 898<h4 id="features-arrays-destructuring">5.2.4 Destructuring</h4> 899 900<p>Array literals may be used on the left-hand side of an assignment to perform 901destructuring (such as when unpacking multiple values from a single array or 902iterable). A final <q>rest</q> element may be included (with no space between the 903<code>...</code> and the variable name). Elements should be omitted if they are unused.</p> 904 905<pre><code class="language-js prettyprint">const [a, b, c, ...rest] = generateResults(); 906let [, b,, d] = someArray; 907</code></pre> 908 909<p>Destructuring may also be used for function parameters (note that a parameter 910name is required but ignored). Always specify <code>[]</code> as the default value if a 911destructured array parameter is optional, and provide default values on the left 912hand side:</p> 913 914<pre><code class="language-js prettyprint">/** @param {!Array<number>=} param1 */ 915function optionalDestructuring([a = 4, b = 2] = []) { … }; 916</code></pre> 917 918<p>Illegal:</p> 919 920<pre><code class="language-js prettyprint badcode">function badDestructuring([a, b] = [4, 2]) { … }; 921</code></pre> 922 923<p>Tip: For (un)packing multiple values into a function’s parameter or return, 924prefer object destructuring to array destructuring when possible, as it allows 925naming the individual elements and specifying a different type for each.*</p> 926 927<h4 id="features-arrays-spread-operator">5.2.5 Spread operator</h4> 928 929<p>Array literals may include the spread operator (<code>...</code>) to flatten elements out 930of one or more other iterables. The spread operator should be used instead of 931more awkward constructs with <code>Array.prototype</code>. There is no space after the 932<code>...</code>.</p> 933 934<p>Example:</p> 935 936<pre><code class="language-js prettyprint">[...foo] // preferred over Array.prototype.slice.call(foo) 937[...foo, ...bar] // preferred over foo.concat(bar) 938</code></pre> 939 940<h3 id="features-object-literals">5.3 Object literals</h3> 941 942<h4 id="features-objects-use-trailing-comma">5.3.1 Use trailing commas</h4> 943 944<p>Include a trailing comma whenever there is a line break between the final 945property and the closing brace.</p> 946 947<h4 id="features-objects-ctor">5.3.2 Do not use the <code>Object</code> constructor</h4> 948 949<p>While <code>Object</code> does not have the same problems as <code>Array</code>, it is still 950disallowed for consistency. Use an object literal (<code>{}</code> or <code>{a: 0, b: 1, c: 2}</code>) 951instead.</p> 952 953<h4 id="features-objects-mixing-keys">5.3.3 Do not mix quoted and unquoted keys</h4> 954 955<p>Object literals may represent either <em>structs</em> (with unquoted keys and/or 956symbols) or <em>dicts</em> (with quoted and/or computed keys). Do not mix these key 957types in a single object literal.</p> 958 959<p>Illegal:</p> 960 961<pre><code class="language-js prettyprint badcode">{ 962 a: 42, // struct-style unquoted key 963 'b': 43, // dict-style quoted key 964} 965</code></pre> 966 967<h4 id="features-objects-computed-property-names">5.3.4 Computed property names</h4> 968 969<p>Computed property names (e.g., <code>{['key' + foo()]: 42}</code>) are allowed, and are 970considered dict-style (quoted) keys (i.e., must not be mixed with non-quoted 971keys) unless the computed property is a symbol (e.g., <code>[Symbol.iterator]</code>). 972Enum values may also be used for computed keys, but should not be mixed with 973non-enum keys in the same literal.</p> 974 975<h4 id="features-objects-method-shorthand">5.3.5 Method shorthand</h4> 976 977<p>Methods can be defined on object literals using the method shorthand (<code>{method() 978{… }}</code>) in place of a colon immediately followed by a <code>function</code> or arrow 979function literal.</p> 980 981<p>Example:</p> 982 983<pre><code class="language-js prettyprint">return { 984 stuff: 'candy', 985 method() { 986 return this.stuff; // Returns 'candy' 987 }, 988}; 989</code></pre> 990 991<p>Note that <code>this</code> in a method shorthand or <code>function</code> refers to the object 992literal itself whereas <code>this</code> in an arrow function refers to the scope outside 993the object literal.</p> 994 995<p>Example:</p> 996 997<pre><code class="language-js prettyprint">class { 998 getObjectLiteral() { 999 this.stuff = 'fruit'; 1000 return { 1001 stuff: 'candy', 1002 method: () => this.stuff, // Returns 'fruit' 1003 }; 1004 } 1005} 1006</code></pre> 1007 1008<h4 id="features-objects-shorthand-properties">5.3.6 Shorthand properties</h4> 1009 1010<p>Shorthand properties are allowed on object literals.</p> 1011 1012<p>Example:</p> 1013 1014<pre><code class="language-js prettyprint">const foo = 1; 1015const bar = 2; 1016const obj = { 1017 foo, 1018 bar, 1019 method() { return this.foo + this.bar; }, 1020}; 1021assertEquals(3, obj.method()); 1022</code></pre> 1023 1024<h4 id="features-objects-destructuring">5.3.7 Destructuring</h4> 1025 1026<p>Object destructuring patterns may be used on the left-hand side of an assignment 1027to perform destructuring and unpack multiple values from a single object.</p> 1028 1029<p>Destructured objects may also be used as function parameters, but should be kept 1030as simple as possible: a single level of unquoted shorthand properties. Deeper 1031levels of nesting and computed properties may not be used in parameter 1032destructuring. Specify any default values in the left-hand-side of the 1033destructured parameter (<code>{str = 'some default'} = {}</code>, rather than <code class="badcode">{str} = {str: 'some default'}</code>), and if a destructured 1034object is itself optional, it must default to <code>{}</code>. The JSDoc for the 1035destructured parameter may be given any name (the name is unused but is required 1036by the compiler).</p> 1037 1038<p>Example:</p> 1039 1040<pre><code class="language-js prettyprint">/** 1041 * @param {string} ordinary 1042 * @param {{num: (number|undefined), str: (string|undefined)}=} param1 1043 * num: The number of times to do something. 1044 * str: A string to do stuff to. 1045 */ 1046function destructured(ordinary, {num, str = 'some default'} = {}) 1047</code></pre> 1048 1049<p>Illegal:</p> 1050 1051<pre><code class="language-js prettyprint badcode">/** @param {{x: {num: (number|undefined), str: (string|undefined)}}} param1 */ 1052function nestedTooDeeply({x: {num, str}}) {}; 1053/** @param {{num: (number|undefined), str: (string|undefined)}=} param1 */ 1054function nonShorthandProperty({num: a, str: b} = {}) {}; 1055/** @param {{a: number, b: number}} param1 */ 1056function computedKey({a, b, [a + b]: c}) {}; 1057/** @param {{a: number, b: string}=} param1 */ 1058function nontrivialDefault({a, b} = {a: 2, b: 4}) {}; 1059</code></pre> 1060 1061<p>Destructuring may also be used for <code>goog.require</code> statements, and in this case 1062must not be wrapped: the entire statement occupies one line, regardless of how 1063long it is (see <a href="#file-goog-require">??</a>).</p> 1064 1065<h4 id="features-objects-enums">5.3.8 Enums</h4> 1066 1067<p>Enumerations are defined by adding the <code>@enum</code> annotation to an object literal. 1068Additional properties may not be added to an enum after it is defined. Enums 1069must be constant, and all enum values must be deeply immutable.</p> 1070 1071<pre><code class="language-js prettyprint">/** 1072 * Supported temperature scales. 1073 * @enum {string} 1074 */ 1075const TemperatureScale = { 1076 CELSIUS: 'celsius', 1077 FAHRENHEIT: 'fahrenheit', 1078}; 1079 1080/** 1081 * An enum with two options. 1082 * @enum {number} 1083 */ 1084const Option = { 1085 /** The option used shall have been the first. */ 1086 FIRST_OPTION: 1, 1087 /** The second among two options. */ 1088 SECOND_OPTION: 2, 1089}; 1090</code></pre> 1091 1092<h3 id="features-classes">5.4 Classes</h3> 1093 1094<h4 id="features-classes-constructors">5.4.1 Constructors</h4> 1095 1096<p>Constructors are optional for concrete classes. Subclass constructors must call 1097<code>super()</code> before setting any fields or otherwise accessing <code>this</code>. Interfaces 1098must not define a constructor.</p> 1099 1100<h4 id="features-classes-fields">5.4.2 Fields</h4> 1101 1102<p>Set all of a concrete object’s fields (i.e. all properties other than methods) 1103in the constructor. Annotate fields that are never reassigned with <code>@const</code> 1104(these need not be deeply immutable). Private fields must be annotated with 1105<code>@private</code> and their names must end with a trailing underscore. Fields are never 1106set on a concrete class' <code>prototype</code>.</p> 1107 1108<p>Example:</p> 1109 1110<pre><code class="language-js prettyprint">class Foo { 1111 constructor() { 1112 /** @private @const {!Bar} */ 1113 this.bar_ = computeBar(); 1114 } 1115} 1116</code></pre> 1117 1118<p>Tip: Properties should never be added to or removed from an instance after the 1119constructor is finished, since it significantly hinders VMs’ ability to 1120optimize. If necessary, fields that are initialized later should be explicitly 1121set to <code>undefined</code> in the constructor to prevent later shape changes. Adding 1122<code>@struct</code> to an object will check that undeclared properties are not 1123added/accessed. Classes have this added by default.</p> 1124 1125<h4 id="features-classes-computed-properties">5.4.3 Computed properties</h4> 1126 1127 1128 1129<p>Computed properties may only be used in classes when the property is a 1130symbol. Dict-style properties (that is, quoted or computed non-symbol keys, as 1131defined in <a href="#features-objects-mixing-keys">??</a>) are not allowed. A 1132<code>[Symbol.iterator]</code> method should be defined for any classes that are logically 1133iterable. Beyond this, <code>Symbol</code> should be used sparingly.</p> 1134 1135<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> 1136 1137<h4 id="features-classes-static-methods">5.4.4 Static methods</h4> 1138 1139 1140 1141<p>Where it does not interfere with readability, prefer module-local functions over 1142private static methods.</p> 1143 1144<p>Static methods should only be called on the base class itself. Static methods 1145should not be called on variables containing a dynamic instance that may be 1146either the constructor or a subclass constructor (and must be defined with 1147<code>@nocollapse</code> if this is done), and must not be called directly on a subclass 1148that doesn’t define the method itself.</p> 1149 1150<p>Illegal:</p> 1151 1152<pre><code class="language-js prettyprint badcode">class Base { /** @nocollapse */ static foo() {} } 1153class Sub extends Base {} 1154function callFoo(cls) { cls.foo(); } // discouraged: don't call static methods dynamically 1155Sub.foo(); // illegal: don't call static methods on subclasses that don't define it themselves 1156</code></pre> 1157 1158<h4 id="features-classes-old-style">5.4.5 Old-style class declarations</h4> 1159 1160<p>While ES6 classes are preferred, there are cases where ES6 classes may not be 1161feasible. For example:</p> 1162 1163<ol> 1164<li><p>If there exist or will exist subclasses, including frameworks that create 1165subclasses, that cannot be immediately changed to use ES6 class syntax. If 1166such a class were to use ES6 syntax, all downstream subclasses not using ES6 1167class syntax would need to be modified.</p></li> 1168<li><p>Frameworks that require a known <code>this</code> value before calling the superclass 1169constructor, since constructors with ES6 super classes do not have 1170access to the instance <code>this</code> value until the call to <code>super</code> returns.</p></li> 1171</ol> 1172 1173<p>In all other ways the style guide still applies to this code: <code>let</code>, <code>const</code>, 1174default parameters, rest, and arrow functions should all be used when 1175appropriate.</p> 1176 1177<p><code>goog.defineClass</code> allows for a class-like definition similar to ES6 class 1178syntax:</p> 1179 1180<pre><code class="language-javascript">let C = goog.defineClass(S, { 1181 /** 1182 * @param {string} value 1183 */ 1184 constructor(value) { 1185 S.call(this, 2); 1186 /** @const */ 1187 this.prop = value; 1188 }, 1189 1190 /** 1191 * @param {string} param 1192 * @return {number} 1193 */ 1194 method(param) { 1195 return 0; 1196 }, 1197}); 1198</code></pre> 1199 1200<p>Alternatively, while <code>goog.defineClass</code> should be preferred for all new code, 1201more traditional syntax is also allowed.</p> 1202 1203<pre><code class="language-javascript">/** 1204 * @constructor @extends {S} 1205 * @param {string} value 1206 */ 1207function C(value) { 1208 S.call(this, 2); 1209 /** @const */ 1210 this.prop = value; 1211} 1212goog.inherits(C, S); 1213 1214/** 1215 * @param {string} param 1216 * @return {number} 1217 */ 1218C.prototype.method = function(param) { 1219 return 0; 1220}; 1221</code></pre> 1222 1223<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> 1224 1225<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> 1226 1227<h4 id="features-classes-prototypes">5.4.6 Do not manipulate <code>prototype</code>s directly</h4> 1228 1229<p>The <code>class</code> keyword allows clearer and more readable class definitions than 1230defining <code>prototype</code> properties. Ordinary implementation code has no business 1231manipulating these objects, though they are still useful for defining <code>@record</code> 1232interfaces and classes as defined in <a href="#features-classes-old-style">??</a>. Mixins 1233and modifying the prototypes of builtin objects are 1234explicitly forbidden.</p> 1235 1236<p><strong>Exception</strong>: Framework code (such as Polymer, or Angular) may need to use <code>prototype</code>s, and should not 1237resort to even-worse workarounds to avoid doing so.</p> 1238 1239<p><strong>Exception</strong>: Defining fields in interfaces (see <a href="#features-classes-interfaces">??</a>).</p> 1240 1241<h4 id="features-classes-getters-and-setters">5.4.7 Getters and Setters</h4> 1242 1243<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 1244surprising and difficult to reason about, and have limited support in the 1245compiler. Provide ordinary methods instead.</p> 1246 1247<p><strong>Exception</strong>: when working with data binding frameworks (such as Angular and 1248Polymer), getters and setters may be used sparingly. Note, however, that 1249compiler support is limited. When they are used, they must be defined either 1250with <code>get foo()</code> and <code>set foo(value)</code> in the class or object literal, or if that 1251is not possible, with <code>Object.defineProperties</code>. Do not use 1252<code>Object.defineProperty</code>, which interferes with property renaming. Getters 1253<strong>must not</strong> change observable state.</p> 1254 1255<p>Illegal:</p> 1256 1257<pre><code class="language-js prettyprint badcode">class Foo { 1258 get next() { return this.nextId++; } 1259} 1260</code></pre> 1261 1262<h4 id="features-classes-overriding-tostring">5.4.8 Overriding toString</h4> 1263 1264<p>The <code>toString</code> method may be overridden, but must always succeed and never have 1265visible side effects.</p> 1266 1267<p>Tip: Beware, in particular, of calling other methods from toString, since 1268exceptional conditions could lead to infinite loops.</p> 1269 1270<h4 id="features-classes-interfaces">5.4.9 Interfaces</h4> 1271 1272<p>Interfaces may be declared with <code>@interface</code> or <code>@record</code>. Interfaces declared 1273with <code>@record</code> can be explicitly (i.e. via <code>@implements</code>) or implicitly 1274implemented by a class or object literal.</p> 1275 1276<p>All non-static method bodies on an interface must be empty blocks. Fields must 1277be defined after the interface body as stubs on the <code>prototype</code>.</p> 1278 1279<p>Example:</p> 1280 1281<pre><code class="language-js prettyprint">/** 1282 * Something that can frobnicate. 1283 * @record 1284 */ 1285class Frobnicator { 1286 /** 1287 * Performs the frobnication according to the given strategy. 1288 * @param {!FrobnicationStrategy} strategy 1289 */ 1290 frobnicate(strategy) {} 1291} 1292 1293/** @type {number} The number of attempts before giving up. */ 1294Frobnicator.prototype.attempts; 1295</code></pre> 1296 1297<h3 id="features-functions">5.5 Functions</h3> 1298 1299<h4 id="features-functions-top-level-functions">5.5.1 Top-level functions</h4> 1300 1301<p>Exported functions may be defined directly on the <code>exports</code> object, or else 1302declared locally and exported separately. Non-exported functions are encouraged 1303and should not be declared <code>@private</code>.</p> 1304 1305<p>Examples:</p> 1306 1307<pre><code class="language-js prettyprint">/** @return {number} */ 1308function helperFunction() { 1309 return 42; 1310} 1311/** @return {number} */ 1312function exportedFunction() { 1313 return helperFunction() * 2; 1314} 1315/** 1316 * @param {string} arg 1317 * @return {number} 1318 */ 1319function anotherExportedFunction(arg) { 1320 return helperFunction() / arg.length; 1321} 1322/** @const */ 1323exports = {exportedFunction, anotherExportedFunction}; 1324</code></pre> 1325 1326<pre><code class="language-js prettyprint">/** @param {string} arg */ 1327exports.foo = (arg) => { 1328 // do some stuff ... 1329}; 1330</code></pre> 1331 1332<h4 id="features-functions-nested-functions">5.5.2 Nested functions and closures</h4> 1333 1334<p>Functions may contain nested function definitions. If it is useful to give the 1335function a name, it should be assigned to a local <code>const</code>.</p> 1336 1337<h4 id="features-functions-arrow-functions">5.5.3 Arrow functions</h4> 1338 1339<p>Arrow functions provide a concise syntax and fix a number of difficulties with 1340<code>this</code>. Prefer arrow functions over the <code>function</code> keyword, particularly for 1341nested functions (but see <a href="#features-objects-method-shorthand">??</a>).</p> 1342 1343<p>Prefer using arrow functions over <code>f.bind(this)</code>, and especially over 1344<code>goog.bind(f, this)</code>. Avoid writing <code>const self = this</code>. Arrow functions are 1345particularly useful for callbacks, which sometimes pass unexpected additional 1346arguments.</p> 1347 1348<p>The right-hand side of the arrow may be a single expression or a block. 1349Parentheses around the arguments are optional if there is only a single 1350non-destructured argument.</p> 1351 1352<p>Tip: It is a good practice to use parentheses even for single-argument arrows, 1353since the code may still parse reasonably (but incorrectly) if the parentheses 1354are forgotten when an additional argument is added.</p> 1355 1356<h4 id="features-functions-generators">5.5.4 Generators</h4> 1357 1358<p>Generators enable a number of useful abstractions and may be used as needed.</p> 1359 1360<p>When defining generator functions, attach the <code>*</code> to the <code>function</code> keyword when 1361present, and separate it with a space from the name of the function. When using 1362delegating yields, attach the <code>*</code> to the <code>yield</code> keyword.</p> 1363 1364<p>Example:</p> 1365 1366<pre><code class="language-js prettyprint">/** @return {!Iterator<number>} */ 1367function* gen1() { 1368 yield 42; 1369} 1370 1371/** @return {!Iterator<number>} */ 1372const gen2 = function*() { 1373 yield* gen1(); 1374} 1375 1376class SomeClass { 1377 /** @return {!Iterator<number>} */ 1378 * gen() { 1379 yield 42; 1380 } 1381} 1382</code></pre> 1383 1384<h4 id="features-functions-parameters">5.5.5 Parameters</h4> 1385 1386<p>Function parameters must be typed with JSDoc annotations in the JSDoc preceding 1387the function’s definition, except in the case of same-signature <code>@override</code>s, 1388where all types are omitted.</p> 1389 1390<p>Parameter types <em>may</em> be specified inline, immediately before the parameter name 1391(as in <code>(/** number */ foo, /** string */ bar) => foo + bar</code>). Inline and 1392<code>@param</code> type annotations <em>must not</em> be mixed in the same function definition.</p> 1393 1394<h5 id="features-functions-default-parameters">5.5.5.1 Default parameters</h5> 1395 1396<p>Optional parameters are permitted using the equals operator in the parameter 1397list. Optional parameters must include spaces on both sides of the equals 1398operator, be named exactly like required parameters (i.e., not prefixed with 1399<code>opt_</code>), use the <code>=</code> suffix in their JSDoc type, come after required parameters, 1400and not use initializers that produce observable side effects. All optional 1401parameters must have a default value in the function declaration, even if that 1402value is <code>undefined</code>.</p> 1403 1404<p>Example:</p> 1405 1406<pre><code class="language-js prettyprint">/** 1407 * @param {string} required This parameter is always needed. 1408 * @param {string=} optional This parameter can be omitted. 1409 * @param {!Node=} node Another optional parameter. 1410 */ 1411function maybeDoSomething(required, optional = '', node = undefined) {} 1412</code></pre> 1413 1414<p>Use default parameters sparingly. Prefer destructuring (as in 1415<a href="#features-objects-destructuring">??</a>) to create readable APIs when there 1416are more than a small handful of optional parameters that do not have a natural 1417order.</p> 1418 1419<p>Note: Unlike Python's default parameters, it is okay to use initializers that 1420return new mutable objects (such as <code>{}</code> or <code>[]</code>) because the initializer is 1421evaluated each time the default value is used, so a single object won't be 1422shared across invocations.</p> 1423 1424<p>Tip: While arbitrary expressions including function calls may be used as 1425initializers, these should be kept as simple as possible. Avoid initializers 1426that expose shared mutable state, as that can easily introduce unintended 1427coupling between function calls.</p> 1428 1429<h5 id="features-functions-rest-parameters">5.5.5.2 Rest parameters</h5> 1430 1431<p>Use a <em>rest</em> parameter instead of accessing <code>arguments</code>. Rest parameters are 1432typed with a <code>...</code> prefix in their JSDoc. The rest parameter must be the last 1433parameter in the list. There is no space between the <code>...</code> and the parameter 1434name. Do not name the rest parameter <code>var_args</code>. Never name a local variable or 1435parameter <code>arguments</code>, which confusingly shadows the built-in name.</p> 1436 1437<p>Example:</p> 1438 1439<pre><code class="language-js prettyprint">/** 1440 * @param {!Array<string>} array This is an ordinary parameter. 1441 * @param {...number} numbers The remainder of arguments are all numbers. 1442 */ 1443function variadic(array, ...numbers) {} 1444</code></pre> 1445 1446<h4 id="features-functions-returns">5.5.6 Returns</h4> 1447 1448<p>Function return types must be specified in the JSDoc directly above the function 1449definition, except in the case of same-signature <code>@override</code>s where all types 1450are omitted.</p> 1451 1452<h4 id="features-functions-generics">5.5.7 Generics</h4> 1453 1454<p>Declare generic functions and methods when necessary with <code>@template TYPE</code> in 1455the JSDoc above the class definition.</p> 1456 1457<h4 id="features-functions-spread-operator">5.5.8 Spread operator</h4> 1458 1459<p>Function calls may use the spread operator (<code>...</code>). Prefer the spread operator 1460to <code>Function.prototype.apply</code> when an array or iterable is unpacked into 1461multiple parameters of a variadic function. There is no space after the <code>...</code>.</p> 1462 1463<p>Example:</p> 1464 1465<pre><code class="language-js prettyprint">function myFunction(...elements) {} 1466myFunction(...array, ...iterable, ...generator()); 1467</code></pre> 1468 1469<h3 id="features-string-literals">5.6 String literals</h3> 1470 1471<h4 id="features-strings-use-single-quotes">5.6.1 Use single quotes</h4> 1472 1473<p>Ordinary string literals are delimited with single quotes (<code>'</code>), rather than 1474double quotes (<code>"</code>).</p> 1475 1476<p>Tip: if a string contains a single quote character, consider using a template 1477string to avoid having to escape the quote.</p> 1478 1479<p>Ordinary string literals may not span multiple lines.</p> 1480 1481<h4 id="features-strings-template-strings">5.6.2 Template strings</h4> 1482 1483<p>Use template strings (delimited with <code>`</code>) over complex string 1484concatenation, particularly if multiple string literals are involved. Template 1485strings may span multiple lines.</p> 1486 1487<p>If a template string spans multiple lines, it does not need to follow the 1488indentation of the enclosing block, though it may if the added whitespace does 1489not matter.</p> 1490 1491<p>Example:</p> 1492 1493<pre><code class="language-js prettyprint">function arithmetic(a, b) { 1494 return `Here is a table of arithmetic operations: 1495${a} + ${b} = ${a + b} 1496${a} - ${b} = ${a - b} 1497${a} * ${b} = ${a * b} 1498${a} / ${b} = ${a / b}`; 1499} 1500</code></pre> 1501 1502<h4 id="features-strings-no-line-continuations">5.6.3 No line continuations</h4> 1503 1504<p>Do not use <em>line continuations</em> (that is, ending a line inside a string literal 1505with a backslash) in either ordinary or template string literals. Even though 1506ES5 allows this, it can lead to tricky errors if any trailing whitespace comes 1507after the slash, and is less obvious to readers.</p> 1508 1509<p>Illegal:</p> 1510 1511<pre><code class="language-js prettyprint badcode">const longString = 'This is a very long string that far exceeds the 80 \ 1512 column limit. It unfortunately contains long stretches of spaces due \ 1513 to how the continued lines are indented.'; 1514</code></pre> 1515 1516<p>Instead, write</p> 1517 1518<pre><code class="language-js prettyprint">const longString = 'This is a very long string that far exceeds the 80 ' + 1519 'column limit. It does not contain long stretches of spaces since ' + 1520 'the concatenated strings are cleaner.'; 1521</code></pre> 1522 1523<h3 id="features-number-literals">5.7 Number literals</h3> 1524 1525<p>Numbers may be specified in decimal, hex, octal, or binary. Use exactly <code>0x</code>, 1526<code>0o</code>, and <code>0b</code> prefixes, with lowercase letters, for hex, octal, and binary, 1527respectively. Never include a leading zero unless it is immediately followed by 1528<code>x</code>, <code>o</code>, or <code>b</code>.</p> 1529 1530<h3 id="features-control-structures">5.8 Control structures</h3> 1531 1532<h4 id="features-for-loops">5.8.1 For loops</h4> 1533 1534<p>With ES6, the language now has three different kinds of <code>for</code> loops. All may be 1535used, though <code>for</code>-<code>of</code> loops should be preferred when possible.</p> 1536 1537<p><code>for</code>-<code>in</code> loops may only be used on dict-style objects (see 1538<a href="#features-objects-mixing-keys">??</a>), and should not be used to iterate over an 1539array. <code>Object.prototype.hasOwnProperty</code> should be used in <code>for</code>-<code>in</code> loops to 1540exclude unwanted prototype properties. Prefer <code>for</code>-<code>of</code> and <code>Object.keys</code> over 1541<code>for</code>-<code>in</code> when possible.</p> 1542 1543<h4 id="features-exceptions">5.8.2 Exceptions</h4> 1544 1545<p>Exceptions are an important part of the language and should be used whenever 1546exceptional cases occur. Always throw <code>Error</code>s or subclasses of <code>Error</code>: never 1547throw string literals or other objects. Always use <code>new</code> when constructing an 1548<code>Error</code>.</p> 1549 1550<p>Custom exceptions provide a great way to convey additional error information 1551from functions. They should be defined and used wherever the native <code>Error</code> 1552type is insufficient.</p> 1553 1554<p>Prefer throwing exceptions over ad-hoc error-handling approaches (such as 1555passing an error container reference type, or returning an object with an error 1556property).</p> 1557 1558<h5 id="features-empty-catch-blocks">5.8.2.1 Empty catch blocks</h5> 1559 1560<p>It is very rarely correct to do nothing in response to a caught exception. When 1561it truly is appropriate to take no action whatsoever in a catch block, the 1562reason this is justified is explained in a comment.</p> 1563 1564<pre><code class="language-js prettyprint">try { 1565 return handleNumericResponse(response); 1566} catch (ok) { 1567 // it's not numeric; that's fine, just continue 1568} 1569return handleTextResponse(response); 1570</code></pre> 1571 1572<p>Illegal:</p> 1573 1574<pre><code class="language-js prettyprint badcode"> try { 1575 shouldFail(); 1576 fail('expected an error'); 1577 } 1578 catch (expected) {} 1579</code></pre> 1580 1581<p>Tip: Unlike in some other languages, patterns like the above simply don’t work 1582since this will catch the error thrown by <code>fail</code>. Use <code>assertThrows()</code> instead.</p> 1583 1584<h4 id="features-switch-statements">5.8.3 Switch statements</h4> 1585 1586<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> 1587 1588<h5 id="features-switch-fall-through">5.8.3.1 Fall-through: commented</h5> 1589 1590<p>Within a switch block, each statement group either terminates abruptly (with a 1591<code>break</code>, <code>return</code> or <code>throw</code>n exception), or is marked with a comment to 1592indicate that execution will or might continue into the next statement 1593group. Any comment that communicates the idea of fall-through is sufficient 1594(typically <code>// fall through</code>). This special comment is not required in the last 1595statement group of the switch block.</p> 1596 1597<p>Example:</p> 1598 1599<pre><code class="language-js prettyprint">switch (input) { 1600 case 1: 1601 case 2: 1602 prepareOneOrTwo(); 1603 // fall through 1604 case 3: 1605 handleOneTwoOrThree(); 1606 break; 1607 default: 1608 handleLargeNumber(input); 1609} 1610</code></pre> 1611 1612<h5 id="features-switch-default-case">5.8.3.2 The <code>default</code> case is present</h5> 1613 1614<p>Each switch statement includes a <code>default</code> statement group, even if it contains 1615no code.</p> 1616 1617<h3 id="features-this">5.9 this</h3> 1618 1619<p>Only use <code>this</code> in class constructors and methods, or in arrow functions defined 1620within class constructors and methods. Any other uses of <code>this</code> must have an 1621explicit <code>@this</code> declared in the immediately-enclosing function’s JSDoc.</p> 1622 1623<p>Never use <code>this</code> to refer to the global object, the context of an <code>eval</code>, the 1624target of an event, or unnecessarily <code>call()</code>ed or <code>apply()</code>ed functions.</p> 1625 1626<h3 id="disallowed-features">5.10 Disallowed features</h3> 1627 1628<h4 id="disallowed-features-with">5.10.1 with</h4> 1629 1630<p>Do not use the <code>with</code> keyword. It makes your code harder to understand and has 1631been banned in strict mode since ES5.</p> 1632 1633<h4 id="disallowed-features-dynamic-code-evaluation">5.10.2 Dynamic code evaluation</h4> 1634 1635<p>Do not use <code>eval</code> or the <code>Function(...string)</code> constructor (except for code 1636loaders). These features are potentially dangerous and simply do not work in 1637CSP environments.</p> 1638 1639<h4 id="disallowed-features-automatic-semicolon-insertion">5.10.3 Automatic semicolon insertion</h4> 1640 1641<p>Always terminate statements with semicolons (except function and class 1642declarations, as noted above).</p> 1643 1644<h4 id="disallowed-features-non-standard-features">5.10.4 Non-standard features</h4> 1645 1646<p>Do not use non-standard features. This includes old features that have been 1647removed (e.g., <code>WeakMap.clear</code>), new features that are not yet standardized 1648(e.g., the current TC39 working draft, proposals at any stage, or proposed but 1649not-yet-complete web standards), or proprietary features that are only 1650implemented in some browsers. Use only features defined in the current ECMA-262 1651or WHATWG standards. (Note that projects writing against specific APIs, such as 1652Chrome extensions or Node.js, can obviously use those APIs). Non-standard 1653language “extensions” (such as those provided by some external transpilers) are 1654forbidden.</p> 1655 1656<h4 id="disallowed-features-wrapper-objects">5.10.5 Wrapper objects for primitive types</h4> 1657 1658<p>Never use <code>new</code> on the primitive object wrappers (<code>Boolean</code>, <code>Number</code>, <code>String</code>, 1659<code>Symbol</code>), nor include them in type annotations.</p> 1660 1661<p>Illegal:</p> 1662 1663<pre><code class="language-js prettyprint badcode">const /** Boolean */ x = new Boolean(false); 1664if (x) alert(typeof x); // alerts 'object' - WAT? 1665</code></pre> 1666 1667<p>The wrappers may be called as functions for coercing (which is preferred over 1668using <code>+</code> or concatenating the empty string) or creating symbols.</p> 1669 1670<p>Example:</p> 1671 1672<pre><code class="language-js prettyprint">const /** boolean */ x = Boolean(0); 1673if (!x) alert(typeof x); // alerts 'boolean', as expected 1674</code></pre> 1675 1676<h4 id="disallowed-features-modifying-builtin-objects">5.10.6 Modifying builtin objects</h4> 1677 1678<p>Never modify builtin types, either by adding methods to their constructors or to 1679their prototypes. Avoid depending on libraries that do this. Note that the 1680JSCompiler’s runtime library will provide standards-compliant polyfills where 1681possible; nothing else may modify builtin objects.</p> 1682 1683<p>Do not add symbols to the global object unless absolutely necessary 1684(e.g. required by a third-party API).</p> 1685 1686<h2 id="naming">6 Naming</h2> 1687 1688<h3 id="naming-rules-common-to-all-identifiers">6.1 Rules common to all identifiers</h3> 1689 1690<p>Identifiers use only ASCII letters and digits, and, in a small number of cases 1691noted below, underscores and very rarely (when required by frameworks like 1692Angular) dollar signs.</p> 1693 1694<p>Give as descriptive a name as possible, within reason. Do not worry about saving 1695horizontal space as it is far more important to make your code immediately 1696understandable by a new reader. Do not use abbreviations that are ambiguous or 1697unfamiliar to readers outside your project, and do not abbreviate by deleting 1698letters within a word.</p> 1699 1700<pre><code class="language-js prettyprint">priceCountReader // No abbreviation. 1701numErrors // "num" is a widespread convention. 1702numDnsConnections // Most people know what "DNS" stands for. 1703</code></pre> 1704 1705<p>Illegal:</p> 1706 1707<pre><code class="language-js prettyprint badcode">n // Meaningless. 1708nErr // Ambiguous abbreviation. 1709nCompConns // Ambiguous abbreviation. 1710wgcConnections // Only your group knows what this stands for. 1711pcReader // Lots of things can be abbreviated "pc". 1712cstmrId // Deletes internal letters. 1713kSecondsPerDay // Do not use Hungarian notation. 1714</code></pre> 1715 1716<h3 id="naming-rules-by-identifier-type">6.2 Rules by identifier type</h3> 1717 1718<h4 id="naming-package-names">6.2.1 Package names</h4> 1719 1720<p>Package names are all <code>lowerCamelCase</code>. For example, 1721<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> 1722 1723<h4 id="naming-class-names">6.2.2 Class names</h4> 1724 1725<p>Class, interface, record, and typedef names are written in <code>UpperCamelCase</code>. 1726Unexported classes are simply locals: they are not marked <code>@private</code> and 1727therefore are not named with a trailing underscore.</p> 1728 1729<p>Type names are typically nouns or noun phrases. For example, <code>Request</code>, 1730<code>ImmutableList</code>, or <code>VisibilityMode</code>. Additionally, interface names may 1731sometimes be adjectives or adjective phrases instead (for example, <code>Readable</code>).</p> 1732 1733<h4 id="naming-method-names">6.2.3 Method names</h4> 1734 1735<p>Method names are written in <code>lowerCamelCase</code>. Private methods’ names must end 1736with a trailing underscore.</p> 1737 1738<p>Method names are typically verbs or verb phrases. For example, <code>sendMessage</code> or 1739<code>stop_</code>. Getter and setter methods for properties are never required, but if 1740they are used they should be named <code>getFoo</code> (or optionally <code>isFoo</code> or <code>hasFoo</code> 1741for booleans), or <code>setFoo(value)</code> for setters.</p> 1742 1743<p>Underscores may also appear in JsUnit test method names to separate logical 1744components of the name. One typical pattern is <code>test<MethodUnderTest>_<state></code>, 1745for example <code>testPop_emptyStack</code>. There is no One Correct Way to name test 1746methods.</p> 1747 1748<h4 id="naming-enum-names">6.2.4 Enum names</h4> 1749 1750<p>Enum names are written in <code>UpperCamelCase</code>, similar to classes, and should 1751generally be singular nouns. Individual items within the enum are named in 1752<code>CONSTANT_CASE</code>.</p> 1753 1754<h4 id="naming-constant-names">6.2.5 Constant names</h4> 1755 1756<p>Constant names use <code>CONSTANT_CASE</code>: all uppercase letters, with words separated 1757by underscores. There is no reason for a constant to be named with a trailing 1758underscore, since private static properties can be replaced by (implicitly 1759private) module locals.</p> 1760 1761<h5 id="naming-definition-of-constant">6.2.5.1 Definition of “constant”</h5> 1762 1763<p>Every constant is a <code>@const</code> static property or a module-local <code>const</code> 1764declaration, but not all <code>@const</code> static properties and module-local <code>const</code>s 1765are constants. Before choosing constant case, consider whether the field really 1766feels like a <em>deeply immutable</em> constant. For example, if any of that instance's 1767observable state can change, it is almost certainly not a constant. Merely 1768intending to never mutate the object is generally not enough.</p> 1769 1770<p>Examples:</p> 1771 1772<pre><code class="language-js prettyprint">// Constants 1773const NUMBER = 5; 1774/** @const */ exports.NAMES = ImmutableList.of('Ed', 'Ann'); 1775/** @enum */ exports.SomeEnum = { ENUM_CONSTANT: 'value' }; 1776 1777// Not constants 1778let letVariable = 'non-const'; 1779class MyClass { constructor() { /** @const */ this.nonStatic = 'non-static'; } }; 1780/** @type {string} */ MyClass.staticButMutable = 'not @const, can be reassigned'; 1781const /** Set<String> */ mutableCollection = new Set(); 1782const /** ImmutableSet<SomeMutableType> */ mutableElements = ImmutableSet.of(mutable); 1783const Foo = goog.require('my.Foo'); // mirrors imported name 1784const logger = log.getLogger('loggers.are.not.immutable'); 1785</code></pre> 1786 1787<p>Constants’ names are typically nouns or noun phrases.</p> 1788 1789<h5 id="naming-local-aliases">6.2.5.1 Local aliases</h5> 1790 1791<p>Local aliases should be used whenever they improve readability over 1792fully-qualified names. Follow the same rules as <code>goog.require</code>s 1793(<a href="#file-goog-require">??</a>), maintaining the last part of the aliased name. 1794Aliases may also be used within functions. Aliases must be <code>const</code>.</p> 1795 1796<p>Examples:</p> 1797 1798<pre><code class="language-js prettyprint">const staticHelper = importedNamespace.staticHelper; 1799const CONSTANT_NAME = ImportedClass.CONSTANT_NAME; 1800const {assert, assertInstanceof} = asserts; 1801</code></pre> 1802 1803<h4 id="naming-non-constant-field-names">6.2.6 Non-constant field names</h4> 1804 1805<p>Non-constant field names (static or otherwise) are written in <code>lowerCamelCase</code>, 1806with a trailing underscore for private fields.</p> 1807 1808<p>These names are typically nouns or noun phrases. For example, <code>computedValues</code> 1809or <code>index_</code>.</p> 1810 1811<h4 id="naming-parameter-names">6.2.7 Parameter names</h4> 1812 1813<p>Parameter names are written in <code>lowerCamelCase</code>. Note that this applies even if 1814the parameter expects a constructor.</p> 1815 1816<p>One-character parameter names should not be used in public methods.</p> 1817 1818<p><strong>Exception</strong>: When required by a third-party framework, parameter names may 1819begin with a <code>$</code>. This exception does not apply to any other identifiers 1820(e.g. local variables or properties).</p> 1821 1822<h4 id="naming-local-variable-names">6.2.8 Local variable names</h4> 1823 1824<p>Local variable names are written in <code>lowerCamelCase</code>, except for module-local 1825(top-level) constants, as described above. Constants in function scopes are 1826still named in <code>lowerCamelCase</code>. Note that lowerCamelCase applies even if the 1827variable holds a constructor.</p> 1828 1829<h4 id="naming-template-parameter-names">6.2.9 Template parameter names</h4> 1830 1831<p>Template parameter names should be concise, single-word or single-letter 1832identifiers, and must be all-caps, such as <code>TYPE</code> or <code>THIS</code>.</p> 1833 1834<h3 id="naming-camel-case-defined">6.3 Camel case: defined</h3> 1835 1836<p>Sometimes there is more than one reasonable way to convert an English phrase 1837into camel case, such as when acronyms or unusual constructs like <q>IPv6</q> or 1838<q>iOS</q> are present. To improve predictability, Google Style specifies the 1839following (nearly) deterministic scheme.</p> 1840 1841<p>Beginning with the prose form of the name:</p> 1842 1843<ol> 1844<li>Convert the phrase to plain ASCII and remove any apostrophes. For example, 1845<q>Müller's algorithm</q> might become <q>Muellers algorithm</q>.</li> 1846<li>Divide this result into words, splitting on spaces and any remaining 1847punctuation (typically hyphens). 1848<ol> 1849<li>Recommended: if any word already has a conventional camel case 1850appearance in common usage, split this into its constituent parts (e.g., 1851<q>AdWords</q> becomes <q>ad words</q>). Note that a word such as <q>iOS</q> is not 1852really in camel case per se; it defies any convention, so this 1853recommendation does not apply.</li> 1854</ol></li> 1855<li>Now lowercase everything (including acronyms), then uppercase only the first 1856character of: 1857<ol> 1858<li>… each word, to yield upper camel case, or</li> 1859<li>… each word except the first, to yield lower camel case</li> 1860</ol></li> 1861<li>Finally, join all the words into a single identifier.</li> 1862</ol> 1863 1864<p>Note that the casing of the original words is almost entirely disregarded.</p> 1865 1866<p>Examples:</p> 1867 1868<table> 1869<thead> 1870<tr> 1871<th style="text-align: center">Prose form</th> 1872<th style="text-align: center">Correct</th> 1873<th style="text-align: center">Incorrect</th> 1874</tr> 1875</thead> 1876 1877<tbody> 1878<tr> 1879<td style="text-align: center"><q>XML HTTP request</q></td> 1880<td style="text-align: center">XmlHttpRequest</td> 1881<td style="text-align: center">XMLHTTPRequest</td> 1882</tr> 1883<tr> 1884<td style="text-align: center"><q>new customer ID</q></td> 1885<td style="text-align: center">newCustomerId</td> 1886<td style="text-align: center">newCustomerID</td> 1887</tr> 1888<tr> 1889<td style="text-align: center"><q>inner stopwatch</q></td> 1890<td style="text-align: center">innerStopwatch</td> 1891<td style="text-align: center">innerStopWatch</td> 1892</tr> 1893<tr> 1894<td style="text-align: center"><q>supports IPv6 on iOS?</q></td> 1895<td style="text-align: center">supportsIpv6OnIos</td> 1896<td style="text-align: center">supportsIPv6OnIOS</td> 1897</tr> 1898<tr> 1899<td style="text-align: center"><q>YouTube importer</q></td> 1900<td style="text-align: center">YouTubeImporter</td> 1901<td style="text-align: center">YoutubeImporter*</td> 1902</tr> 1903</tbody> 1904</table> 1905 1906<p>*Acceptable, but not recommended.</p> 1907 1908<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> 1909 1910<h2 id="jsdoc">7 JSDoc</h2> 1911 1912<p><a href="https://developers.google.com/closure/compiler/docs/js-for-compiler">JSDoc</a> is used on all classes, fields, and methods.</p> 1913 1914<h3 id="jsdoc-general-form">7.1 General form</h3> 1915 1916<p>The basic formatting of JSDoc blocks is as seen in this example:</p> 1917 1918<pre><code class="language-js prettyprint">/** 1919 * Multiple lines of JSDoc text are written here, 1920 * wrapped normally. 1921 * @param {number} arg A number to do something to. 1922 */ 1923function doSomething(arg) { … } 1924</code></pre> 1925 1926<p>or in this single-line example:</p> 1927 1928<pre><code class="language-js prettyprint">/** @const @private {!Foo} A short bit of JSDoc. */ 1929this.foo_ = foo; 1930</code></pre> 1931 1932<p>If a single-line comment overflows into multiple lines, it must use the 1933multi-line style with <code>/**</code> and <code>*/</code> on their own lines.</p> 1934 1935<p>Many tools extract metadata from JSDoc comments to perform code validation and 1936optimization. As such, these comments <strong>must</strong> be well-formed.</p> 1937 1938<h3 id="jsdoc-markdown">7.2 Markdown</h3> 1939 1940<p>JSDoc is written in Markdown, though it may include HTML when necessary.</p> 1941 1942<p>Note that tools that automatically extract JSDoc (e.g. <a href="https://github.com/jleyba/js-dossier">JsDossier</a>) will often 1943ignore plain text formatting, so if you did this:</p> 1944 1945<pre><code class="language-js prettyprint badcode">/** 1946 * Computes weight based on three factors: 1947 * items sent 1948 * items received 1949 * last timestamp 1950 */ 1951</code></pre> 1952 1953<p>it would come out like this:</p> 1954 1955<pre><code>Computes weight based on three factors: items sent items received last timestamp 1956</code></pre> 1957 1958<p>Instead, write a Markdown list:</p> 1959 1960<pre><code class="language-js prettyprint">/** 1961 * Computes weight based on three factors: 1962 * - items sent 1963 * - items received 1964 * - last timestamp 1965 */ 1966</code></pre> 1967 1968<h3 id="jsdoc-tags">7.3 JSDoc tags</h3> 1969 1970<p>Google style allows a subset of JSDoc tags. See 1971<a href="#appendices-jsdoc-tag-reference">??</a> for the complete list. Most tags must 1972occupy their own line, with the tag at the beginning of the line.</p> 1973 1974<p>Illegal:</p> 1975 1976<pre><code class="language-js prettyprint badcode">/** 1977 * The "param" tag must occupy its own line and may not be combined. 1978 * @param {number} left @param {number} right 1979 */ 1980function add(left, right) { ... } 1981</code></pre> 1982 1983<p>Simple tags that do not require any additional data (such as <code>@private</code>, 1984<code>@const</code>, <code>@final</code>, <code>@export</code>) may be combined onto the same line, along with an 1985optional type when appropriate.</p> 1986 1987<pre><code class="language-js prettyprint">/** 1988 * Place more complex annotations (like "implements" and "template") 1989 * on their own lines. Multiple simple tags (like "export" and "final") 1990 * may be combined in one line. 1991 * @export @final 1992 * @implements {Iterable<TYPE>} 1993 * @template TYPE 1994 */ 1995class MyClass { 1996 /** 1997 * @param {!ObjType} obj Some object. 1998 * @param {number=} num An optional number. 1999 */ 2000 constructor(obj, num = 42) { 2001 /** @private @const {!Array<!ObjType|number>} */ 2002 this.data_ = [obj, num]; 2003 } 2004} 2005</code></pre> 2006 2007<p>There is no hard rule for when to combine tags, or in which order, but be 2008consistent.</p> 2009 2010<p>For general information about annotating types in JavaScript see 2011<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 2012System</a>.</p> 2013 2014<h3 id="jsdoc-line-wrapping">7.4 Line wrapping</h3> 2015 2016<p>Line-wrapped block tags are indented four spaces. Wrapped description text may 2017be lined up with the description on previous lines, but this horizontal 2018alignment is discouraged.</p> 2019 2020<pre><code class="language-js prettyprint">/** 2021 * Illustrates line wrapping for long param/return descriptions. 2022 * @param {string} foo This is a param with a description too long to fit in 2023 * one line. 2024 * @return {number} This returns something that has a description too long to 2025 * fit in one line. 2026 */ 2027exports.method = function(foo) { 2028 return 5; 2029}; 2030</code></pre> 2031 2032<p>Do not indent when wrapping a <code>@fileoverview</code> description.</p> 2033 2034<h3 id="jsdoc-top-file-level-comments">7.5 Top/file-level comments</h3> 2035 2036<p>A file may have a top-level file overview. A copyright notice , author information, and 2037default <a href="#jsdoc-visibility-annotations">visibility level</a> are optional. File overviews are generally recommended whenever a 2038file consists of more than a single class definition. The top level comment is 2039designed to orient readers unfamiliar with the code to what is in this file. If 2040present, it may provide a description of the file's contents and any 2041dependencies or compatibility information. Wrapped lines are not indented.</p> 2042 2043<p>Example:</p> 2044 2045<pre><code class="language-js prettyprint">/** 2046 * @fileoverview Description of file, its uses and information 2047 * about its dependencies. 2048 * @package 2049 */ 2050</code></pre> 2051 2052<h3 id="jsdoc-class-comments">7.6 Class comments</h3> 2053 2054<p>Classes, interfaces and records must be documented with a description and any 2055template parameters, implemented interfaces, visibility, or other appropriate 2056tags. The class description should provide the reader with enough information to 2057know how and when to use the class, as well as any additional considerations 2058necessary to correctly use the class. Textual descriptions may be omitted on the 2059constructor. <code>@constructor</code> and <code>@extends</code> annotations are not used with the 2060<code>class</code> keyword unless the class is being used to declare an <code>@interface</code> or 2061it extends a generic class.</p> 2062 2063<pre><code class="language-js prettyprint">/** 2064 * A fancier event target that does cool things. 2065 * @implements {Iterable<string>} 2066 */ 2067class MyFancyTarget extends EventTarget { 2068 /** 2069 * @param {string} arg1 An argument that makes this more interesting. 2070 * @param {!Array<number>} arg2 List of numbers to be processed. 2071 */ 2072 constructor(arg1, arg2) { 2073 // ... 2074 } 2075}; 2076 2077/** 2078 * Records are also helpful. 2079 * @extends {Iterator<TYPE>} 2080 * @record 2081 * @template TYPE 2082 */ 2083class Listable { 2084 /** @return {TYPE} The next item in line to be returned. */ 2085 next() {} 2086} 2087</code></pre> 2088 2089<h3 id="jsdoc-enum-and-typedef-comments">7.7 Enum and typedef comments</h3> 2090 2091<p>Enums and typedefs must be documented. Public enums and typedefs must have a 2092non-empty description. Individual enum items may be documented with a JSDoc 2093comment on the preceding line.</p> 2094 2095<pre><code class="language-js prettyprint">/** 2096 * A useful type union, which is reused often. 2097 * @typedef {!Bandersnatch|!BandersnatchType} 2098 */ 2099let CoolUnionType; 2100 2101 2102/** 2103 * Types of bandersnatches. 2104 * @enum {string} 2105 */ 2106const BandersnatchType = { 2107 /** This kind is really frumious. */ 2108 FRUMIOUS: 'frumious', 2109 /** The less-frumious kind. */ 2110 MANXOME: 'manxome', 2111}; 2112</code></pre> 2113 2114<p>Typedefs are useful for defining short record types, or aliases for unions, 2115complex functions, or generic types. 2116Typedefs should be avoided for record types with many fields, since they do not 2117allow documenting individual fields, nor using templates or recursive 2118references. 2119For large record types, prefer <code>@record</code>.</p> 2120 2121<h3 id="jsdoc-method-and-function-comments">7.8 Method and function comments</h3> 2122 2123<p>Parameter and return types must be documented. The <code>this</code> type should be 2124documented when necessary. Method, parameter, and return descriptions (but not 2125types) may be omitted if they are obvious from the rest of the method’s JSDoc or 2126from its signature. Method descriptions should start with a sentence written in 2127the third person declarative voice. If a method overrides a superclass method, 2128it must include an <code>@override</code> annotation. Overridden methods must include all 2129<code>@param</code> and <code>@return</code> annotations if any types are refined, but should omit 2130them if the types are all the same.</p> 2131 2132<pre><code class="language-js prettyprint">/** This is a class. */ 2133class SomeClass extends SomeBaseClass { 2134 /** 2135 * Operates on an instance of MyClass and returns something. 2136 * @param {!MyClass} obj An object that for some reason needs detailed 2137 * explanation that spans multiple lines. 2138 * @param {!OtherClass} obviousOtherClass 2139 * @return {boolean} Whether something occurred. 2140 */ 2141 someMethod(obj, obviousOtherClass) { ... } 2142 2143 /** @override */ 2144 overriddenMethod(param) { ... } 2145} 2146 2147/** 2148 * Demonstrates how top-level functions follow the same rules. This one 2149 * makes an array. 2150 * @param {TYPE} arg 2151 * @return {!Array<TYPE>} 2152 * @template TYPE 2153 */ 2154function makeArray(arg) { ... } 2155</code></pre> 2156 2157 2158 2159<p>Anonymous functions do not require JSDoc, though parameter types may be specified inline if the automatic type inference is insufficient.</p> 2160 2161<pre><code class="language-js prettyprint">promise.then( 2162 (/** !Array<number|string> */ items) => { 2163 doSomethingWith(items); 2164 return /** @type {string} */ (items[0]); 2165 }); 2166</code></pre> 2167 2168<h3 id="jsdoc-property-comments">7.9 Property comments</h3> 2169 2170<p>Property types must be documented. The description may be omitted for private 2171properties, if name and type provide enough documentation for understanding the 2172code.</p> 2173 2174<p>Publicly exported constants are commented the same way as properties. Explicit 2175types may be omitted for <code>@const</code> properties initialized from an expression with 2176an obviously known type.</p> 2177 2178<p>Tip: A <code>@const</code> property’s type can be considered “obviously known” if it is 2179assigned directly from a constructor parameter with a declared type, or directly 2180from a function call with a declared return type. Non-const properties and 2181properties assigned from more complex expressions should have their types 2182declared explicitly.</p> 2183 2184<pre><code class="language-js prettyprint">/** My class. */ 2185class MyClass { 2186 /** @param {string=} someString */ 2187 constructor(someString = 'default string') { 2188 /** @private @const */ 2189 this.someString_ = someString; 2190 2191 /** @private @const {!OtherType} */ 2192 this.someOtherThing_ = functionThatReturnsAThing(); 2193 2194 /** 2195 * Maximum number of things per pane. 2196 * @type {number} 2197 */ 2198 this.someProperty = 4; 2199 } 2200} 2201 2202/** 2203 * The number of times we'll try before giving up. 2204 * @const 2205 */ 2206MyClass.RETRY_COUNT = 33; 2207</code></pre> 2208 2209<h3 id="jsdoc-type-annotations">7.10 Type annotations</h3> 2210 2211<p>Type annotations are found on <code>@param</code>, <code>@return</code>, <code>@this</code>, and <code>@type</code> tags, 2212and optionally on <code>@const</code>, <code>@export</code>, and any visibility tags. Type 2213annotations attached to JSDoc tags must always be enclosed in braces.</p> 2214 2215<h4 id="jsdoc-nullability">7.10.1 Nullability</h4> 2216 2217<p>The type system defines modifiers <code>!</code> and <code>?</code> for non-null and nullable, 2218respectively. Primitive types (<code>undefined</code>, <code>string</code>, <code>number</code>, <code>boolean</code>, 2219<code>symbol</code>, and <code>function(...): ...</code>) and record literals (<code>{foo: string, bar: 2220number}</code>) are non-null by default. Do not add an explicit <code>!</code> to these types. 2221Object types (<code>Array</code>, <code>Element</code>, <code>MyClass</code>, etc) are nullable by default, but 2222cannot be immediately distinguished from a name that is <code>@typedef</code>’d to a 2223non-null-by-default type. As such, all types except primitives and record 2224literals must be annotated explicitly with either <code>?</code> or <code>!</code> to indicate whether 2225they are nullable or not.</p> 2226 2227<h4 id="jsdoc-type-casts">7.10.2 Type Casts</h4> 2228 2229<p>In cases where type checking doesn't accurately infer the type of an expression, 2230it is possible to tighten the type by adding a type annotation comment and 2231enclosing the expression in parentheses. Note that the parentheses are required.</p> 2232 2233<pre><code class="language-js prettyprint">/** @type {number} */ (x) 2234</code></pre> 2235 2236<h4 id="jsdoc-template-parameter-types">7.10.3 Template Parameter Types</h4> 2237 2238<p>Always specify template parameters. This way compiler can do a better job and it 2239makes it easier for readers to understand what code does.</p> 2240 2241<p>Bad:</p> 2242 2243<pre><code class="language-js prettyprint badcode">const /** !Object */ users = {}; 2244const /** !Array */ books = []; 2245const /** !Promise */ response = ...; 2246</code></pre> 2247 2248<p>Good:</p> 2249 2250<pre><code class="language-js prettyprint">const /** !Object<string, !User> */ users = {}; 2251const /** !Array<string> */ books = []; 2252const /** !Promise<!Response> */ response = ...; 2253 2254const /** !Promise<undefined> */ thisPromiseReturnsNothingButParameterIsStillUseful = ...; 2255const /** !Object<string, *> */ mapOfEverything = {}; 2256</code></pre> 2257 2258<p>Cases when template parameters should not be used:</p> 2259 2260<ul> 2261<li><code>Object</code> is used for type hierarchy and not as map-like structure.</li> 2262</ul> 2263 2264<h3 id="jsdoc-visibility-annotations">7.11 Visibility annotations</h3> 2265 2266<p>Visibility annotations (<code>@private</code>, <code>@package</code>, <code>@protected</code>) may be specified 2267in a <code>@fileoverview</code> block, or on any exported symbol or property. Do not 2268specify visibility for local variables, whether within a function or at the top 2269level of a module. All <code>@private</code> names must end with an underscore.</p> 2270 2271<h2 id="policies">8 Policies</h2> 2272 2273<h3 id="policies-be-consistent">8.1 Issues unspecified by Google Style: Be Consistent!</h3> 2274 2275<p>For any style question that isn't settled definitively by this specification, 2276prefer to do what the other code in the same file is already doing. If that 2277doesn't resolve the question, consider emulating the other files in the same 2278package.</p> 2279 2280<h3 id="policies-compiler-warnings">8.2 Compiler warnings</h3> 2281 2282<h4 id="policies-use-a-standard-warning-set">8.2.1 Use a standard warning set</h4> 2283 2284<p> 2285As far as possible projects should use <code>--warning_level=VERBOSE</code>. 2286</p> 2287 2288<h4 id="policies-how-to-handle-a-warning">8.2.2 How to handle a warning</h4> 2289 2290<p>Before doing anything, make sure you understand exactly what the warning is 2291telling you. If you're not positive why a warning is appearing, ask for help 2292.</p> 2293 2294<p>Once you understand the warning, attempt the following solutions in order:</p> 2295 2296<ol> 2297<li><strong>First, fix it or work around it.</strong> Make a strong attempt to actually 2298address the warning, or find another way to accomplish the task that avoids 2299the situation entirely.</li> 2300<li><strong>Otherwise, determine if it's a false alarm.</strong> If you are convinced that 2301the warning is invalid and that the code is actually safe and correct, add a 2302comment to convince the reader of this fact and apply the <code>@suppress</code> 2303annotation.</li> 2304<li><strong>Otherwise, leave a TODO comment.</strong> This is a <strong>last resort</strong>. If you do 2305this, <strong>do not suppress the warning.</strong> The warning should be visible until 2306it can be taken care of properly.</li> 2307</ol> 2308 2309<h4 id="policies-suppress-a-warning-at-the-narrowest-reasonable-scope">8.2.3 Suppress a warning at the narrowest reasonable scope</h4> 2310 2311<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> 2312 2313<p>Example</p> 2314 2315<pre><code class="language-js prettyprint">/** @suppress {uselessCode} Unrecognized 'use asm' declaration */ 2316function fn() { 2317 'use asm'; 2318 return 0; 2319} 2320</code></pre> 2321 2322<p>Even a large number of suppressions in a class is still better than blinding the 2323entire class to this type of warning.</p> 2324 2325<h3 id="policies-deprecation">8.3 Deprecation</h3> 2326 2327<p>Mark deprecated methods, classes or interfaces with <code>@deprecated</code> annotations. A 2328deprecation comment must include simple, clear directions for people to fix 2329their call sites.</p> 2330 2331<h3 id="policies-code-not-in-google-style">8.4 Code not in Google Style</h3> 2332 2333<p>You will occasionally encounter files in your codebase that are not in proper 2334Google Style. These may have come from an acquisition, or may have been written 2335before Google Style took a position on some issue, or may be in non-Google Style 2336for any other reason.</p> 2337 2338<h4 id="policies-reformatting-existing-code">8.4.1 Reformatting existing code</h4> 2339 2340<p>When updating the style of existing code, follow these guidelines.</p> 2341 2342<ol> 2343<li>It is not required to change all existing code to meet current style 2344guidelines. Reformatting existing code is a trade-off between code churn 2345and consistency. Style rules evolve over time and these kinds of tweaks to 2346maintain compliance would create unnecessary churn. However, if significant 2347changes are being made to a file it is expected that the file will be in 2348Google Style.</li> 2349<li>Be careful not to allow opportunistic style fixes to muddle the focus of a 2350CL. If you find yourself making a lot of style changes that aren’t critical 2351to the central focus of a CL, promote those changes to a separate CL.</li> 2352</ol> 2353 2354<h4 id="policies-newly-added-code-use-google-style">8.4.2 Newly added code: use Google Style</h4> 2355 2356<p>Brand new files use Google Style, regardless of the style choices of other files 2357in the same package.</p> 2358 2359<p>When adding new code to a file that is not in Google Style, reformatting the 2360existing code first is recommended, subject to the advice in 2361<a href="#policies-reformatting-existing-code">??</a>.</p> 2362 2363<p>If this reformatting is not done, then new code should be as consistent as 2364possible with existing code in the same file, but must not violate the style 2365guide.</p> 2366 2367<h3 id="policies-local-style-rules">8.5 Local style rules</h3> 2368 2369<p>Teams and projects may adopt additional style rules beyond those in this 2370document, but must accept that cleanup changes may not abide by these additional 2371rules, and must not block such cleanup changes due to violating any additional 2372rules. Beware of excessive rules which serve no purpose. The style guide does 2373not seek to define style in every possible scenario and neither should you.</p> 2374 2375<h3 id="policies-generated-code-mostly-exempt">8.6 Generated code: mostly exempt</h3> 2376 2377<p>Source code generated by the build process is not required to be in Google 2378Style. However, any generated identifiers that will be referenced from 2379hand-written source code must follow the naming requirements. As a special 2380exception, such identifiers are allowed to contain underscores, which may help 2381to avoid conflicts with hand-written identifiers.</p> 2382 2383<h2 id="appendices">9 Appendices</h2> 2384 2385<h3 id="appendices-jsdoc-tag-reference">9.1 JSDoc tag reference</h3> 2386 2387<p>JSDoc serves multiple purposes in JavaScript. In addition to being used to 2388generate documentation it is also used to control tooling. The best known are 2389the Closure Compiler type annotations.</p> 2390 2391<h4 id="appendices-type-annotations">9.1.1 Type annotations and other Closure Compiler annotations</h4> 2392 2393<p>Documentation for JSDoc used by the Closure Compiler is described in 2394<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 2395System</a>.</p> 2396 2397<h4 id="appendices-documentation-annotations">9.1.2 Documentation annotations</h4> 2398 2399<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 2400Compiler</a> the following tags are common and well supported by various 2401documentation generations tools (such as <a href="https://github.com/jleyba/js-dossier">JsDossier</a>) for purely documentation 2402purposes. 2403<table> 2404 <thead> 2405 <tr> 2406 <th>Tag 2407 </th><th>Template & Examples 2408 </th><th>Description 2409 </th></tr></thead><tbody> 2410 <tr> 2411 <td><code>@author</code> or <code>@owner</code> 2412 </td><td><code>@author username@google.com (First Last)</code> 2413 <p><em>For example:</em> 2414 </p><pre class="prettyprint lang-js"> 2415/** 2416 * @fileoverview Utilities for handling textareas. 2417 * @author <a href="mailto:kuth@google.com">kuth@google.com</a> (Uthur Pendragon) 2418 */ 2419 </pre> 2420 </td><td>Document the author of a file or the owner of a test, generally only 2421 used in the <code>@fileoverview</code> comment. The <code>@owner</code> tag is used by the 2422 unit test dashboard to determine who owns the test results. 2423 <p>Not recommended. 2424 </p></td></tr><tr> 2425 <td><code>@bug</code> 2426 </td><td><code>@bug bugnumber</code> 2427 <p><em>For example:</em> 2428 </p><pre class="prettyprint lang-js"> 2429/** @bug 1234567 */ 2430function testSomething() { 2431 // … 2432} 2433 2434<p>/** 2435 * @bug 1234568 2436 * @bug 1234569 2437 */ 2438function testTwoBugs() { 2439 // … 2440} 2441</p></pre> 2442 </td><td>Indicates what bugs the given test function regression tests. 2443 <p>Multiple bugs should each have their own <code>@bug</code> line, to make 2444 searching for regression tests as easy as possible. 2445 </p></td></tr><tr> 2446 <td><code>@code</code> 2447 </td><td><code>{@code ...}</code> 2448 <p><em>For example:</em> 2449 </p><pre class="prettyprint lang-js"> 2450/** 2451 * Moves to the next position in the selection. 2452 * Throws {@code goog.iter.StopIteration} when it 2453 * passes the end of the range. 2454 * @return {!Node} The node at the next position. 2455 */ 2456goog.dom.RangeIterator.prototype.next = function() { 2457 // … 2458}; 2459</pre> 2460 </td><td>Indicates that a term in a JSDoc description is code so it may be 2461 correctly formatted in generated documentation. 2462 </td></tr><tr> 2463 <td><code>@see</code> 2464 </td><td><code>@see Link</code> 2465 <p><em>For example:</em> 2466 </p><pre class="prettyprint lang-js"> 2467/** 2468 * Adds a single item, recklessly. 2469 * @see #addSafely 2470 * @see goog.Collect 2471 * @see goog.RecklessAdder#add 2472 */ 2473 </pre> 2474 </td><td>Reference a lookup to another class function or method. 2475 </td></tr><tr> 2476 <td><code>@supported</code> 2477 </td><td><code>@supported Description</code> 2478 <p><em>For example:</em> 2479 </p><pre class="prettyprint lang-js"> 2480/** 2481 * @fileoverview Event Manager 2482 * Provides an abstracted interface to the 2483 * browsers' event systems. 2484 * @supported IE10+, Chrome, Safari 2485 */ 2486</pre> 2487 </td><td>Used in a fileoverview to indicate what browsers are supported by 2488 the file. 2489 </td></tr><tr> 2490 <td><code>@desc</code> 2491 </td><td><code>@desc Message description</code> 2492 <p><em>For example:</em> 2493 </p><pre class="prettyprint lang-js"> 2494/** @desc Notifying a user that their account has been created. */ 2495exports.MSG_ACCOUNT_CREATED = goog.getMsg( 2496 'Your account has been successfully created.'); 2497 </pre> 2498 </td></tr></tbody></table></p> 2499 2500<p>You may also see other types of JSDoc annotations in third-party code. These 2501annotations appear in the <a href="http://code.google.com/p/jsdoc-toolkit/wiki/TagReference">JSDoc Toolkit Tag Reference</a> but are not considered 2502part of valid Google style.</p> 2503 2504<h4 id="appendices-framework-specific-annotations">9.1.3 Framework specific annotations</h4> 2505 2506<p>The following annotations are specific to a particular framework. 2507<table> 2508 <thead> 2509 <tr> 2510 <th>Framework 2511 </th><th>Tag 2512 </th><th>Documentation 2513 </th></tr></thead><tbody> 2514 <tr> 2515 <td>Angular 1 2516 </td><td><code>@ngInject</code> 2517 </td></tr><tr> 2518 <td>Polymer 2519 </td><td><code>@polymerBehavior</code> 2520 </td><td> 2521 2522 <a href="https://github.com/google/closure-compiler/wiki/Polymer-Pass">https://github.com/google/closure-compiler/wiki/Polymer-Pass</a> 2523 2524 </td></tr></tbody></table></p> 2525 2526<h4 id="appendices-notes-about-standard-closure-compiler-annotations">9.1.4 Notes about standard Closure Compiler annotations</h4> 2527 2528<p>The following tags used to be standard but are now deprecated. 2529<table> 2530 <thead> 2531 <tr> 2532 <th>Tag 2533 </th><th>Template & Examples 2534 </th><th>Description 2535 </th></tr></thead><tbody> 2536 <tr> 2537 <td><code>@expose</code> 2538 </td><td><code>@expose</code> 2539 </td><td><strong>Deprecated. Do not use. Use <code>@export</code> and/or <code>@nocollapse</code> 2540 instead.</strong> 2541 </td></tr><tr> 2542 <td><code>@inheritDoc</code> 2543 </td><td><code>@inheritDoc</code> 2544 </td><td><strong>Deprecated. Do not use. Use <code>@override</code> instead.</strong> 2545</td></tr></tbody></table></p> 2546 2547<h3 id="appendices-commonly-misunderstood-style-rules">9.2 Commonly misunderstood style rules</h3> 2548 2549<p>Here is a collection of lesser-known or commonly misunderstood facts about 2550Google Style for JavaScript. (The following are true statements; this is not a 2551list of <q>myths.</q>)</p> 2552 2553<ul> 2554<li>Neither a copyright statement nor <code>@author</code> credit is required in a source 2555file. (Neither is explicitly recommended, either.)</li> 2556<li>Aside from the constructor coming first 2557(<a href="#features-classes-constructors">??</a>), there is no <q>hard and fast</q> rule 2558governing how to order the members of a class (<a href="#features-classes">??</a>).</li> 2559<li>Empty blocks can usually be represented concisely as <code>{}</code>, as detailed in 2560(<a href="#formatting-empty-blocks">??</a>).</li> 2561<li>The prime directive of line-wrapping is: prefer to break at a higher 2562syntactic level (<a href="#formatting-where-to-break">??</a>).</li> 2563<li>Non-ASCII characters are allowed in string literals, comments and Javadoc, 2564and in fact are recommended when they make the code easier to read than the 2565equivalent Unicode escape would (<a href="#non-ascii-characters">??</a>).</li> 2566</ul> 2567 2568<h3 id="appendices-style-related-tools">9.3 Style-related tools</h3> 2569 2570<p>The following tools exist to support various aspects of Google Style.</p> 2571 2572<h4 id="appendices-tools-closure-compiler">9.3.1 Closure Compiler</h4> 2573 2574<p>This program performs type checking and other checks, 2575optimizations and other transformations (such as ECMAScript 6 to ECMAScript 5 2576code lowering).</p> 2577 2578<h4 id="appendices-clang-format">9.3.2 <code>clang-format</code></h4> 2579 2580<p>This program reformats 2581JavaScript source code into Google Style, and also follows a number of 2582non-required but frequently readability-enhancing formatting practices.</p> 2583 2584<p><code>clang-format</code> is not required. Authors are allowed to change its output, and 2585reviewers are allowed to ask for such changes; disputes are worked out in the 2586usual way. However, subtrees may choose to opt in to such enforcement locally.</p> 2587 2588<h4 id="appendices-closure-compiler-linter">9.3.3 Closure compiler linter</h4> 2589 2590<p>This program checks for a 2591variety of missteps and anti-patterns. 2592</p> 2593 2594<h4 id="appendices-conformance-framework">9.3.4 Conformance framework</h4> 2595 2596<p>The JS Conformance Framework is a tool that is part of the Closure Compiler that 2597provides developers a simple means to specify a set of additional checks to be 2598run against their code base above the standard checks. Conformance checks can, 2599for example, forbid access to a certain property, or calls to a certain 2600function, or missing type information (unknowns).</p> 2601 2602<p>These rules are commonly used to enforce critical restrictions (such as defining 2603globals, which could break the codebase) and security patterns (such as using 2604<code>eval</code> or assigning to <code>innerHTML</code>), or more loosely to improve code quality.</p> 2605 2606<p>For additional information see the official documentation for the 2607<a href="https://github.com/google/closure-compiler/wiki/JS-Conformance-Framework">JS Conformance Framework</a>.</p> 2608 2609<h3 id="appendices-legacy-exceptions">9.4 Exceptions for legacy platforms</h3> 2610 2611<h4 id="appendices-legacy-exceptions-overview">9.4.1 Overview</h4> 2612 2613<p>This section describes exceptions and additional rules to be followed when 2614modern ECMAScript 6 syntax is not available to the code authors. Exceptions to 2615the recommended style are required when ECMAScript 6 syntax is not possible and 2616are outlined here:</p> 2617 2618<ul> 2619<li>Use of <code>var</code> declarations is allowed</li> 2620<li>Use of <code>arguments</code> is allowed</li> 2621<li>Optional parameters without default values are allowed</li> 2622</ul> 2623 2624<h4 id="appendices-legacy-exceptions-var">9.4.2 Use <code>var</code></h4> 2625 2626<h5 id="appendices-legacy-exceptions-var-scope">9.4.2.1 <code>var</code> declarations are NOT block-scoped</h5> 2627 2628<p><code>var</code> declarations are scoped to the beginning of the nearest enclosing 2629function, script or module, which can cause unexpected behavior, especially with 2630function closures that reference <code>var</code> declarations inside of loops. The 2631following code gives an example:</p> 2632 2633<pre><code class="language-js prettyprint badcode">for (var i = 0; i < 3; ++i) { 2634 var iteration = i; 2635 setTimeout(function() { console.log(iteration); }, i*1000); 2636} 2637 2638// logs 2, 2, 2 -- NOT 0, 1, 2 2639// because `iteration` is function-scoped, not local to the loop. 2640 2641</code></pre> 2642 2643<h5 id="appendices-legacy-exceptions-var-declare">9.4.2.2 Declare variables as close as possible to first use</h5> 2644 2645<p>Even though <code>var</code> declarations are scoped to the beginning of the enclosing 2646function, <code>var</code> declarations should be as close as possible to their first use, 2647for readability purposes. However, do not put a <code>var</code> declaration inside a block 2648if that variable is referenced outside the block. For example:</p> 2649 2650<pre><code class="language-js prettyprint">function sillyFunction() { 2651 var count = 0; 2652 for (var x in y) { 2653 // "count" could be declared here, but don't do that. 2654 count++; 2655 } 2656 console.log(count + ' items in y'); 2657} 2658</code></pre> 2659 2660<h5 id="appendices-legacy-exceptions-var-const">9.4.2.3 Use @const for constants variables</h5> 2661 2662<p>For global declarations where the <code>const</code> keyword would be used, if it were 2663available, annotate the <code>var</code> declaration with @const instead (this is optional 2664for local variables).</p> 2665 2666<h4 id="appendices-legacy-exceptions-function">9.4.3 Do not use block scoped functions declarations</h4> 2667 2668<p>Do <strong>not</strong> do this:</p> 2669 2670<pre><code class="language-js prettyprint badcode">if (x) { 2671 function foo() {} 2672} 2673</code></pre> 2674 2675<p>While most JavaScript VMs implemented before ECMAScript 6 support function 2676declarations within blocks it was not standardized. Implementations were 2677inconsistent with each other and with the now-standard ECMAScript 6 behavior for 2678block scoped function declaration. ECMAScript 5 and prior only allow for 2679function declarations in the root statement list of a script or function and 2680explicitly ban them in block scopes in strict mode.</p> 2681 2682<p>To get consistent behavior, instead use a <code>var</code> initialized with a function 2683expression to define a function within a block:</p> 2684 2685<pre><code class="language-js prettyprint">if (x) { 2686 var foo = function() {}; 2687} 2688</code></pre> 2689 2690<h4 id="appendices-legacy-exceptions-goog-provide">9.4.4 Dependency management with <code>goog.provide</code>/<code>goog.require</code></h4> 2691 2692<p><strong><code>goog.provide</code> is deprecated. All new files should use <code>goog.module</code>, even in 2693projects with existing <code>goog.provide</code> usage. The following rules are for 2694pre-existing goog.provide files, only.</strong></p> 2695 2696<h5 id="appendices-legacy-exceptions-goog-provide-summary">9.4.4.1 Summary</h5> 2697 2698<ul> 2699<li>Place all <code>goog.provide</code>s first, <code>goog.require</code>s second. Separate provides 2700from requires with an empty line.</li> 2701<li>Sort the entries alphabetically (uppercase first).</li> 2702<li>Don't wrap <code>goog.provide</code> and <code>goog.require</code> statements. Exceed 80 columns 2703if necessary.</li> 2704<li>Only provide top-level symbols.</li> 2705</ul> 2706 2707<p>As of Oct 2016, <strong><code>goog.provide</code>/<code>goog.require</code> dependency management is 2708deprecated</strong>. All new files, even in projects using <code>goog.provide</code> for older 2709files, should use 2710<a href="#source-file-structure"><code>goog.module</code></a>.</p> 2711 2712<p><code>goog.provide</code> statements should be grouped together and placed first. All 2713<code>goog.require</code> statements should follow. The two lists should be separated with 2714an empty line.</p> 2715 2716<p>Similar to import statements in other languages, <code>goog.provide</code> and 2717<code>goog.require</code> statements should be written in a single line, even if they 2718exceed the 80 column line length limit.</p> 2719 2720<p>The lines should be sorted alphabetically, with uppercase letters coming first:</p> 2721 2722<pre><code class="language-js prettyprint">goog.provide('namespace.MyClass'); 2723goog.provide('namespace.helperFoo'); 2724 2725goog.require('an.extremelyLongNamespace.thatSomeoneThought.wouldBeNice.andNowItIsLonger.Than80Columns'); 2726goog.require('goog.dom'); 2727goog.require('goog.dom.TagName'); 2728goog.require('goog.dom.classes'); 2729goog.require('goog.dominoes'); 2730 2731</code></pre> 2732 2733<p>All members defined on a class should be in the same file. Only top-level 2734classes should be provided in a file that contains multiple members defined on 2735the same class (e.g. enums, inner classes, etc).</p> 2736 2737<p>Do this:</p> 2738 2739<pre><code class="language-js prettyprint">goog.provide('namespace.MyClass'); 2740</code></pre> 2741 2742<p>Not this:</p> 2743 2744<pre><code class="language-js prettyprint badcode">goog.provide('namespace.MyClass'); 2745goog.provide('namespace.MyClass.CONSTANT'); 2746goog.provide('namespace.MyClass.Enum'); 2747goog.provide('namespace.MyClass.InnerClass'); 2748goog.provide('namespace.MyClass.TypeDef'); 2749goog.provide('namespace.MyClass.staticMethod'); 2750</code></pre> 2751 2752<p>Members on namespaces may also be provided:</p> 2753 2754<pre><code class="language-js prettyprint">goog.provide('foo.bar'); 2755goog.provide('foo.bar.CONSTANT'); 2756goog.provide('foo.bar.method'); 2757</code></pre> 2758 2759<h5 id="appendices-legacy-exceptions-goog-scope">9.4.4.2 Aliasing with <code>goog.scope</code></h5> 2760 2761<p><strong><code>goog.scope</code> is deprecated. New files should not use <code>goog.scope</code> even in 2762projects with existing goog.scope usage.</strong></p> 2763 2764<p><code>goog.scope</code> may be used to shorten references to namespaced symbols in 2765code using <code>goog.provide</code>/<code>goog.require</code> dependency management.</p> 2766 2767<p>Only one <code>goog.scope</code> invocation may be added per file. Always place it in 2768the global scope.</p> 2769 2770<p>The opening <code>goog.scope(function() {</code> invocation must be preceded by exactly one 2771blank line and follow any <code>goog.provide</code> statements, <code>goog.require</code> statements, 2772or top-level comments. The invocation must be closed on the last line in the 2773file. Append <code>// goog.scope</code> to the closing statement of the scope. Separate the 2774comment from the semicolon by two spaces.</p> 2775 2776<p>Similar to C++ namespaces, do not indent under <code>goog.scope</code> declarations. 2777Instead, continue from the 0 column.</p> 2778 2779<p>Only make aliases for names that will not be re-assigned to another object 2780(e.g., most constructors, enums, and namespaces). Do not do this (see below for 2781how to alias a constructor):</p> 2782 2783<pre><code class="language-js prettyprint badcode">goog.scope(function() { 2784var Button = goog.ui.Button; 2785 2786Button = function() { ... }; 2787... 2788</code></pre> 2789 2790<p>Names must be the same as the last property of the global that they are aliasing.</p> 2791 2792<pre><code class="language-js prettyprint">goog.provide('my.module.SomeType'); 2793 2794goog.require('goog.dom'); 2795goog.require('goog.ui.Button'); 2796 2797goog.scope(function() { 2798var Button = goog.ui.Button; 2799var dom = goog.dom; 2800 2801// Alias new types after the constructor declaration. 2802my.module.SomeType = function() { ... }; 2803var SomeType = my.module.SomeType; 2804 2805// Declare methods on the prototype as usual: 2806SomeType.prototype.findButton = function() { 2807 // Button as aliased above. 2808 this.button = new Button(dom.getElement('my-button')); 2809}; 2810... 2811}); // goog.scope 2812</code></pre> 2813 2814</div> 2815</body> 2816</html> 2817