blob: a80a03235fa1913b72b0c8674d6badb100ee4eb9 [file] [log] [blame]
robbyw@google.combb324012010-07-12 22:02:20 +00001<?xml version = '1.0'?>
2<?xml-stylesheet type="text/xsl" href="styleguide.xsl"?>
3<GUIDE title="Google JavaScript Style Guide">
4 <p class="revision">
5
mark@chromium.org7b245632013-09-25 21:16:00 +00006 Revision 2.93
robbyw@google.combb324012010-07-12 22:02:20 +00007 </p>
8
9 <address>
10 Aaron Whyte<br/>
11 Bob Jervis<br/>
12 Dan Pupius<br/>
mark@chromium.org8190c132013-03-21 16:03:26 +000013 Erik Arvidsson<br/>
robbyw@google.combb324012010-07-12 22:02:20 +000014 Fritz Schneider<br/>
15 Robby Walker<br/>
16 </address>
17 <OVERVIEW>
18 <CATEGORY title="Important Note">
19 <STYLEPOINT title="Displaying Hidden Details in this Guide">
20 <SUMMARY>
21 This style guide contains many details that are initially
22 hidden from view. They are marked by the triangle icon, which you
23 see here on your left. Click it now.
24 You should see "Hooray" appear below.
25 </SUMMARY>
26 <BODY>
27 <p>
28 Hooray! Now you know you can expand points to get more
29 details. Alternatively, there's a "toggle all" at the
30 top of this document.
31 </p>
32 </BODY>
33 </STYLEPOINT>
34 </CATEGORY>
35 <CATEGORY title="Background">
36 <p>
37 JavaScript is the main client-side scripting language used
38
39 by many of Google's open-source
40 projects.
41 This style guide is a list of <em>do</em>s and <em>don't</em>s for
42 JavaScript programs.
43 </p>
44
45
46
mark@chromium.orgc8c76a22012-11-28 20:26:27 +000047
48
robbyw@google.combb324012010-07-12 22:02:20 +000049 </CATEGORY>
50 </OVERVIEW>
51 <CATEGORY title="JavaScript Language Rules">
52
53
mark@chromium.orge33361f2011-11-04 16:55:22 +000054
55
robbyw@google.combb324012010-07-12 22:02:20 +000056 <STYLEPOINT title="var">
57 <SUMMARY>
58 Declarations with <code>var</code>: Always
59 </SUMMARY>
60 <BODY>
61 <DECISION>
62 When you fail to specify <code>var</code>,
63 the variable gets placed in the global context, potentially clobbering
64 existing values. Also, if there's no declaration, it's hard to tell in
65 what scope a variable lives (e.g., it could be in the Document or
66 Window just as easily as in the local scope). So always declare with
67 <code>var</code>.
68 </DECISION>
69 </BODY>
70 </STYLEPOINT>
71
72 <STYLEPOINT title="Constants">
73 <SUMMARY>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +000074 <ul>
75 <li>Use <code>NAMES_LIKE_THIS</code> for constant <em>values</em>.</li>
76 <li>Use <code>@const</code> to indicate a constant (non-overwritable)
77 <em>pointer</em> (a variable or property).</li>
78 <li>Never use the
79 <a href="https://developer.mozilla.org/en/JavaScript/Reference/Statements/const">
80 <code>const</code> keyword</a>
mark@chromium.org7b245632013-09-25 21:16:00 +000081 as it's not supported in Internet Explorer.</li>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +000082 </ul>
robbyw@google.combb324012010-07-12 22:02:20 +000083 </SUMMARY>
84 <BODY>
85 <DECISION>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +000086 <SUBSECTION title="Constant values">
87
88 <p>If a value is intended to be <em>constant</em>
89 and <em>immutable</em>, it should be given a name
90 in <code>CONSTANT_VALUE_CASE</code>.
91 <code>ALL_CAPS</code> additionally implies <code>@const</code>
92 (that the value is not overwritable).
93 </p>
94
95 <p>Primitive types (<code>number</code>, <code>string</code>,
96 <code>boolean</code>) are constant values.</p>
97
98 <p><code>Objects</code>'
mark@chromium.org5684bbc2013-07-12 18:53:13 +000099 immutability is more subjective — objects should be
100 considered immutable only if they do not demonstrate observable
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000101 state change. This is not enforced by the compiler.</p>
102
103
104 </SUBSECTION>
105
106 <SUBSECTION title="Constant pointers (variables and properties)">
107 <p>The <code>@const</code> annotation on a variable or property
108 implies that it is not overwritable. This is enforced by the
109 compiler at build time. This behavior is consistent with the
110 <a href="https://developer.mozilla.org/en/JavaScript/Reference/Statements/const">
111 <code>const</code> keyword</a> (which we do not use due to the
112 lack of support in Internet Explorer).</p>
113
114 <p>A <code>@const</code> annotation on a method additionally
mark@chromium.org7b245632013-09-25 21:16:00 +0000115 implies that the method cannot not be overridden in subclasses.
mark@chromium.org5684bbc2013-07-12 18:53:13 +0000116 </p>
mark@chromium.org7b245632013-09-25 21:16:00 +0000117
118 <p>A <code>@const</code> annotation on a constructor implies the
119 class cannot be subclassed (akin to <code>final</code> in Java).
120 </p>
121
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000122 </SUBSECTION>
123
124 <SUBSECTION title="Examples">
125
126 <p>Note that <code>@const</code> does not necessarily imply
127 <code>CONSTANT_VALUES_CASE</code>.
128
129 However, <code>CONSTANT_VALUES_CASE</code>
130 <em>does</em> imply <code>@const</code>.
131 </p>
132
133 <CODE_SNIPPET>
134 /**
135 * Request timeout in milliseconds.
136 * @type {number}
137 */
138 goog.example.TIMEOUT_IN_MILLISECONDS = 60;
139 </CODE_SNIPPET>
140
141 <p>The number of seconds in a minute never changes. It is a
142 constant value. <code>ALL_CAPS</code>
143 also implies <code>@const</code>, so the constant cannot be
144 overwritten.
145 </p>
146
mark@chromium.org7b245632013-09-25 21:16:00 +0000147 <p>The open source compiler will allow the symbol to be
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000148 overwritten because the constant is
149 <em>not</em> marked as <code>@const</code>.</p>
150
151 <CODE_SNIPPET>
152 /**
153 * Map of URL to response string.
154 * @const
155 */
156 MyClass.fetchedUrlCache_ = new goog.structs.Map();
157 </CODE_SNIPPET>
158
mark@chromium.org7b245632013-09-25 21:16:00 +0000159 <CODE_SNIPPET>
160 /**
161 * Class that cannot be subclassed.
162 * @const
163 * @constructor
164 */
165 sloth.MyFinalClass = function() {};
166 </CODE_SNIPPET>
167
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000168 <p>In this case, the pointer can never be overwritten, but
169 value is highly mutable and <b>not</b> constant (and thus in
170 <code>camelCase</code>, not <code>ALL_CAPS</code>).</p>
171 </SUBSECTION>
172
robbyw@google.combb324012010-07-12 22:02:20 +0000173 </DECISION>
174 </BODY>
175 </STYLEPOINT>
176
177 <STYLEPOINT title="Semicolons">
178 <SUMMARY>
179 Always use semicolons.
180 </SUMMARY>
181 <BODY>
182 <p>Relying on implicit insertion can cause subtle, hard to debug
183 problems. Don't do it. You're better than that.</p>
184 <p>There are a couple places where missing semicolons are particularly
185 dangerous:</p>
186 <BAD_CODE_SNIPPET>
187 // 1.
188 MyClass.prototype.myMethod = function() {
189 return 42;
190 } // No semicolon here.
191
192 (function() {
193 // Some initialization code wrapped in a function to create a scope for locals.
194 })();
195
196
197 var x = {
198 'i': 1,
199 'j': 2
200 } // No semicolon here.
201
202 // 2. Trying to do one thing on Internet Explorer and another on Firefox.
203 // I know you'd never write code like this, but throw me a bone.
mark@chromium.org7b245632013-09-25 21:16:00 +0000204 [ffVersion, ieVersion][isIE]();
robbyw@google.combb324012010-07-12 22:02:20 +0000205
206
207 var THINGS_TO_EAT = [apples, oysters, sprayOnCheese] // No semicolon here.
208
209 // 3. conditional execution a la bash
210 -1 == resultOfOperation() || die();
211 </BAD_CODE_SNIPPET>
212 <SUBSECTION title="So what happens?">
213 <ol>
214 <li>JavaScript error - first the function returning 42 is called
215 with the second function as a parameter, then the number 42 is
216 "called" resulting in an error.</li>
217 <li>You will most likely get a 'no such property in undefined'
218 error at runtime as it tries to call
mark@chromium.org7b245632013-09-25 21:16:00 +0000219 <code>x[ffVersion, ieVersion][isIE]()</code>.</li>
220 <li><code>die</code> is always called since the array minus 1 is
221 <code>NaN</code> which is never equal to anything (not even if
222 <code>resultOfOperation()</code> returns <code>NaN</code>) and
223 <code>THINGS_TO_EAT</code> gets assigned the result of
224 <code>die()</code>.</li>
robbyw@google.combb324012010-07-12 22:02:20 +0000225 </ol>
226 </SUBSECTION>
227 <SUBSECTION title="Why?">
mark@chromium.org5684bbc2013-07-12 18:53:13 +0000228 <p>JavaScript requires statements to end with a semicolon, except when
229 it thinks it can safely infer their existence. In each of these
230 examples, a function declaration or object or array literal is used
231 inside a statement. The closing brackets are not enough to signal
232 the end of the statement. Javascript never ends a statement if the
233 next token is an infix or bracket operator.</p>
robbyw@google.combb324012010-07-12 22:02:20 +0000234 <p>This has really surprised people, so make sure your assignments end
235 with semicolons.</p>
236 </SUBSECTION>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000237 <SUBSECTION title="Clarification: Semicolons and functions">
238 <p>Semicolons should be included at the end of function expressions,
239 but not at the end of function declarations. The distinction is
240 best illustrated with an example:</p>
241 <CODE_SNIPPET>
242 var foo = function() {
243 return true;
244 }; // semicolon here.
245
246 function foo() {
247 return true;
248 } // no semicolon here.
249 </CODE_SNIPPET>
250 </SUBSECTION>
robbyw@google.combb324012010-07-12 22:02:20 +0000251 </BODY>
252 </STYLEPOINT>
253
254 <STYLEPOINT title="Nested functions">
255 <SUMMARY>Yes</SUMMARY>
256 <BODY>
257 <p>Nested functions can be very useful, for example in the creation of
258 continuations and for the task of hiding helper functions. Feel free
259 to use them.</p>
260 </BODY>
261 </STYLEPOINT>
262
mmentovai7ead6442010-10-04 16:26:53 +0000263 <STYLEPOINT title="Function Declarations Within Blocks">
264 <SUMMARY>No</SUMMARY>
265 <BODY>
266 <p>Do not do this:</p>
267 <BAD_CODE_SNIPPET>
268 if (x) {
269 function foo() {}
270 }
271 </BAD_CODE_SNIPPET>
272
273 <p>While most script engines support Function Declarations within blocks
274 it is not part of ECMAScript (see
275 <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMA-262</a>,
276 clause 13 and 14). Worse implementations are inconsistent with each
277 other and with future EcmaScript proposals. ECMAScript only allows for
278 Function Declarations in the root statement list of a script or
279 function. Instead use a variable initialized with a Function
280 Expression to define a function within a block:</p>
281 <CODE_SNIPPET>
282 if (x) {
mark@chromium.org7b245632013-09-25 21:16:00 +0000283 var foo = function() {};
mmentovai7ead6442010-10-04 16:26:53 +0000284 }
285 </CODE_SNIPPET>
286 </BODY>
287 </STYLEPOINT>
288
robbyw@google.combb324012010-07-12 22:02:20 +0000289 <STYLEPOINT title="Exceptions">
290 <SUMMARY>Yes</SUMMARY>
291 <BODY>
292 <p>You basically can't avoid exceptions if you're doing something
293 non-trivial (using an application development framework, etc.).
294 Go for it.</p>
295 </BODY>
296 </STYLEPOINT>
297
298 <STYLEPOINT title="Custom exceptions">
299 <SUMMARY>Yes</SUMMARY>
300 <BODY>
301 <p>Without custom exceptions, returning error information from a
302 function that also returns a value can be tricky, not to mention
303 inelegant. Bad solutions include passing in a reference type to hold
304 error information or always returning Objects with a potential
305 error member. These basically amount to a primitive exception
306 handling hack. Feel free to use custom exceptions when
307 appropriate.</p>
308 </BODY>
309 </STYLEPOINT>
310
311 <STYLEPOINT title="Standards features">
312 <SUMMARY>Always preferred over non-standards features</SUMMARY>
313 <BODY>
314 <p>For maximum portability and compatibility, always prefer standards
315 features over non-standards features (e.g.,
316 <code>string.charAt(3)</code> over <code>string[3]</code> and element
317 access with DOM functions instead of using an application-specific
318 shorthand).</p>
319 </BODY>
320 </STYLEPOINT>
321
322 <STYLEPOINT title="Wrapper objects for primitive types">
323 <SUMMARY>No</SUMMARY>
324 <BODY>
325 <p>There's no reason to use wrapper objects for primitive types, plus
326 they're dangerous:</p>
327 <BAD_CODE_SNIPPET>
328 var x = new Boolean(false);
329 if (x) {
330 alert('hi'); // Shows 'hi'.
331 }
332 </BAD_CODE_SNIPPET>
333 <p>Don't do it!</p>
334 <p>However type casting is fine.</p>
335 <CODE_SNIPPET>
336 var x = Boolean(0);
337 if (x) {
338 alert('hi'); // This will never be alerted.
339 }
340 typeof Boolean(0) == 'boolean';
341 typeof new Boolean(0) == 'object';
342 </CODE_SNIPPET>
343 <p>This is very useful for casting things to
344 <code>number</code>, <code>string</code> and <code>boolean</code>.</p>
345 </BODY>
346 </STYLEPOINT>
347
348 <STYLEPOINT title="Multi-level prototype hierarchies">
349 <SUMMARY>Not preferred</SUMMARY>
350 <BODY>
351 <p>Multi-level prototype hierarchies are how JavaScript implements
352 inheritance. You have a multi-level hierarchy if you have a
353 user-defined class D with another user-defined class B as its
354 prototype. These hierarchies are much harder to get right than they
355 first appear! </p>
356
357 <p>For that reason, it is best to use <code>goog.inherits()</code> from
358 <a href="http://code.google.com/closure/library/">
359 the Closure Library
360 </a>
mark@chromium.org7b245632013-09-25 21:16:00 +0000361 or a similar library function.
robbyw@google.combb324012010-07-12 22:02:20 +0000362 </p>
363 <CODE_SNIPPET>
364 function D() {
365 goog.base(this)
366 }
367 goog.inherits(D, B);
368
369 D.prototype.method = function() {
370 ...
371 };
372 </CODE_SNIPPET>
373 </BODY>
374 </STYLEPOINT>
375
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000376 <STYLEPOINT title="Method and property definitions">
377 <SUMMARY><code>/** @constructor */
378 function SomeConstructor() {
379 this.someProperty = 1;
380 }
381 Foo.prototype.someMethod = function() { ... };</code></SUMMARY>
robbyw@google.combb324012010-07-12 22:02:20 +0000382 <BODY>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000383 <p>While there are several ways to attach methods and properties to an
384 object created via "new", the preferred style for methods
385 is:</p>
robbyw@google.combb324012010-07-12 22:02:20 +0000386 <CODE_SNIPPET>
387 Foo.prototype.bar = function() {
388 /* ... */
389 };
390 </CODE_SNIPPET>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000391 <p>The preferred style for other properties is to initialize the field
392 in the constructor:</p>
393 <CODE_SNIPPET>
394 /** @constructor */
395 function Foo() {
396 this.bar = value;
397 }
398 </CODE_SNIPPET>
399 <SUBSECTION title="Why?">
400 <p>Current JavaScript engines optimize based on the "shape"
401 of an object, <a href="https://developers.google.com/v8/design#prop_access">
402 adding a property to an object (including overriding
403 a value set on the prototype) changes the shape and can degrade
404 performance.</a></p>
405 </SUBSECTION>
406 </BODY>
407 </STYLEPOINT>
408
409 <STYLEPOINT title="delete">
410 <SUMMARY>Prefer <code>this.foo = null</code>.</SUMMARY>
411 <BODY>
412 <CODE_SNIPPET>
413 Foo.prototype.dispose = function() {
414 this.property_ = null;
415 };
416 </CODE_SNIPPET>
417 <p>Instead of:</p>
418 <BAD_CODE_SNIPPET>
419 Foo.prototype.dispose = function() {
420 delete this.property_;
421 };
422 </BAD_CODE_SNIPPET>
423 <p>In modern JavaScript engines, changing the number of properties on an
424 object is much slower than reassigning the values. The delete keyword
425 should be avoided except when it is necessary to remove a property
426 from an object's iterated list of keys, or to change the result of
427 <code>if (key in obj)</code>.</p>
robbyw@google.combb324012010-07-12 22:02:20 +0000428 </BODY>
429 </STYLEPOINT>
430
431 <STYLEPOINT title="Closures">
432 <SUMMARY>Yes, but be careful.</SUMMARY>
433 <BODY>
434 <p>The ability to create closures is perhaps the most useful and often
435 overlooked feature of JS. Here is
436 <a href="http://jibbering.com/faq/faq_notes/closures.html">
mark@chromium.org7b245632013-09-25 21:16:00 +0000437 a good description of how closures work</a>.</p>
robbyw@google.combb324012010-07-12 22:02:20 +0000438 <p>One thing to keep in mind, however, is that a closure keeps a pointer
439 to its enclosing scope. As a result, attaching a closure to a DOM
440 element can create a circular reference and thus, a memory leak. For
441 example, in the following code:</p>
442 <BAD_CODE_SNIPPET>
443 function foo(element, a, b) {
444 element.onclick = function() { /* uses a and b */ };
445 }
446 </BAD_CODE_SNIPPET>
447 <p>the function closure keeps a reference to <code>element</code>,
448 <code>a</code>, and <code>b</code> even if it never uses
449 <code>element</code>. Since <code>element</code> also keeps a
450 reference to the closure, we have a cycle that won't be cleaned up by
451 garbage collection. In these situations, the code can be structured
452 as follows:</p>
453 <CODE_SNIPPET>
454 function foo(element, a, b) {
455 element.onclick = bar(a, b);
456 }
457
458 function bar(a, b) {
mark@chromium.org7b245632013-09-25 21:16:00 +0000459 return function() { /* uses a and b */ };
robbyw@google.combb324012010-07-12 22:02:20 +0000460 }
461 </CODE_SNIPPET>
462 </BODY>
463 </STYLEPOINT>
464
465 <STYLEPOINT title="eval()">
466 <SUMMARY>
mark@chromium.org7b245632013-09-25 21:16:00 +0000467 Only for code loaders and REPL (Read–eval–print loop)
robbyw@google.combb324012010-07-12 22:02:20 +0000468 </SUMMARY>
469 <BODY>
470 <p><code>eval()</code> makes for confusing semantics and is dangerous
471 to use if the string being <code>eval()</code>'d contains user input.
mark@chromium.org7b245632013-09-25 21:16:00 +0000472 There's usually a better, clearer, and safer way to write your code,
473 so its use is generally not permitted.</p>
474
475 <p>For RPC you can always use JSON and read the result using
476 <code>JSON.parse()</code> instead of <code>eval()</code>.</p>
477
478 <p>Let's assume we have a server that returns something like this:</p>
479
robbyw@google.combb324012010-07-12 22:02:20 +0000480 <CODE_SNIPPET>
mark@chromium.org7b245632013-09-25 21:16:00 +0000481 {
482 "name": "Alice",
483 "id": 31502,
484 "email": "looking_glass@example.com"
robbyw@google.combb324012010-07-12 22:02:20 +0000485 }
robbyw@google.combb324012010-07-12 22:02:20 +0000486 </CODE_SNIPPET>
mark@chromium.org7b245632013-09-25 21:16:00 +0000487
488 <BAD_CODE_SNIPPET>
489 var userInfo = eval(feed);
490 var email = userInfo['email'];
491 </BAD_CODE_SNIPPET>
492
493 <p>If the feed was modified to include malicious JavaScript code, then
494 if we use <code>eval</code> then that code will be executed.</p>
495
496 <CODE_SNIPPET>
497 var userInfo = JSON.parse(feed);
498 var email = userInfo['email'];
499 </CODE_SNIPPET>
500
501 <p>With <code>JSON.parse</code>, invalid JSON (including all executable
502 JavaScript) will cause an exception to be thrown.</p>
503
robbyw@google.combb324012010-07-12 22:02:20 +0000504 </BODY>
505 </STYLEPOINT>
506
507 <STYLEPOINT title="with() {}">
508 <SUMMARY>No</SUMMARY>
509 <BODY>
510 <p>Using <code>with</code> clouds the semantics of your program.
511 Because the object of the <code>with</code> can have properties that
512 collide with local variables, it can drastically change the meaning
513 of your program. For example, what does this do?</p>
514 <BAD_CODE_SNIPPET>
515 with (foo) {
516 var x = 3;
517 return x;
518 }
519 </BAD_CODE_SNIPPET>
520 <p>Answer: anything. The local variable <code>x</code> could be
521 clobbered by a property of <code>foo</code> and perhaps it even has
522 a setter, in which case assigning <code>3</code> could cause lots of
523 other code to execute. Don't use <code>with</code>.</p>
524 </BODY>
525 </STYLEPOINT>
526
527 <STYLEPOINT title="this">
528 <SUMMARY>
529 Only in object constructors, methods, and in setting up closures
530 </SUMMARY>
531 <BODY>
532 <p>The semantics of <code>this</code> can be tricky. At times it refers
533 to the global object (in most places), the scope of the caller (in
534 <code>eval</code>), a node in the DOM tree (when attached using an
535 event handler HTML attribute), a newly created object (in a
536 constructor), or some other object (if function was
537 <code>call()</code>ed or <code>apply()</code>ed).</p>
538 <p>Because this is so easy to get wrong, limit its use to those places
539 where it is required:</p>
540 <ul>
541 <li>in constructors</li>
542 <li>in methods of objects (including in the creation of closures)</li>
543 </ul>
544 </BODY>
545 </STYLEPOINT>
546
547 <STYLEPOINT title="for-in loop">
548 <SUMMARY>
549 Only for iterating over keys in an object/map/hash
550 </SUMMARY>
551 <BODY>
552 <p><code>for-in</code> loops are often incorrectly used to loop over
553 the elements in an <code>Array</code>. This is however very error
554 prone because it does not loop from <code>0</code> to
555 <code>length - 1</code> but over all the present keys in the object
556 and its prototype chain. Here are a few cases where it fails:</p>
557 <BAD_CODE_SNIPPET>
558 function printArray(arr) {
559 for (var key in arr) {
560 print(arr[key]);
561 }
562 }
563
564 printArray([0,1,2,3]); // This works.
565
566 var a = new Array(10);
567 printArray(a); // This is wrong.
568
569 a = document.getElementsByTagName('*');
570 printArray(a); // This is wrong.
571
572 a = [0,1,2,3];
573 a.buhu = 'wine';
574 printArray(a); // This is wrong again.
575
576 a = new Array;
577 a[3] = 3;
578 printArray(a); // This is wrong again.
579 </BAD_CODE_SNIPPET>
580 <p>Always use normal for loops when using arrays.</p>
581 <CODE_SNIPPET>
582 function printArray(arr) {
583 var l = arr.length;
584 for (var i = 0; i &lt; l; i++) {
585 print(arr[i]);
586 }
587 }
588 </CODE_SNIPPET>
589 </BODY>
590 </STYLEPOINT>
591
592 <STYLEPOINT title="Associative Arrays">
593 <SUMMARY>
594 Never use <code>Array</code> as a map/hash/associative array
595 </SUMMARY>
596 <BODY>
597 <p>Associative <code>Array</code>s are not allowed... or more precisely
598 you are not allowed to use non number indexes for arrays. If you need
599 a map/hash use <code>Object</code> instead of <code>Array</code> in
600 these cases because the features that you want are actually features
601 of <code>Object</code> and not of <code>Array</code>.
602 <code>Array</code> just happens to extend <code>Object</code> (like
603 any other object in JS and therefore you might as well have used
604 <code>Date</code>, <code>RegExp</code> or <code>String</code>).</p>
605 </BODY>
606 </STYLEPOINT>
607
608 <STYLEPOINT title="Multiline string literals">
609 <SUMMARY>No</SUMMARY>
610 <BODY>
611 <p>Do not do this:</p>
612 <BAD_CODE_SNIPPET>
613 var myString = 'A rather long string of English text, an error message \
614 actually that just keeps going and going -- an error \
615 message to make the Energizer bunny blush (right through \
616 those Schwarzenegger shades)! Where was I? Oh yes, \
617 you\'ve got an error and all the extraneous whitespace is \
618 just gravy. Have a nice day.';
619 </BAD_CODE_SNIPPET>
620 <p>The whitespace at the beginning of each line can't be safely stripped
621 at compile time; whitespace after the slash will result in tricky
622 errors; and while most script engines support this, it is not part
623 of ECMAScript. </p>
mmentovaicd4ce0f2011-03-29 20:30:47 +0000624 <p>Use string concatenation instead:</p>
625 <CODE_SNIPPET>
626 var myString = 'A rather long string of English text, an error message ' +
627 'actually that just keeps going and going -- an error ' +
628 'message to make the Energizer bunny blush (right through ' +
629 'those Schwarzenegger shades)! Where was I? Oh yes, ' +
630 'you\'ve got an error and all the extraneous whitespace is ' +
631 'just gravy. Have a nice day.';
632 </CODE_SNIPPET>
robbyw@google.combb324012010-07-12 22:02:20 +0000633 </BODY>
634 </STYLEPOINT>
635
636 <STYLEPOINT title="Array and Object literals">
637 <SUMMARY>Yes</SUMMARY>
638 <BODY>
639 <p>Use <code>Array</code> and <code>Object</code> literals instead of
640 <code>Array</code> and <code>Object</code> constructors.</p>
641 <p>Array constructors are error-prone due to their arguments.</p>
642 <BAD_CODE_SNIPPET>
643 // Length is 3.
644 var a1 = new Array(x1, x2, x3);
645
646 // Length is 2.
647 var a2 = new Array(x1, x2);
648
649 // If x1 is a number and it is a natural number the length will be x1.
650 // If x1 is a number but not a natural number this will throw an exception.
651 // Otherwise the array will have one element with x1 as its value.
652 var a3 = new Array(x1);
653
654 // Length is 0.
655 var a4 = new Array();
656 </BAD_CODE_SNIPPET>
657 <p>Because of this, if someone changes the code to pass 1 argument
658 instead of 2 arguments, the array might not have the expected
659 length.</p>
660 <p>To avoid these kinds of weird cases, always use the more readable
661 array literal.</p>
662 <CODE_SNIPPET>
663 var a = [x1, x2, x3];
664 var a2 = [x1, x2];
665 var a3 = [x1];
666 var a4 = [];
667 </CODE_SNIPPET>
668 <p>Object constructors don't have the same problems, but for readability
669 and consistency object literals should be used.</p>
670 <BAD_CODE_SNIPPET>
671 var o = new Object();
672
673 var o2 = new Object();
674 o2.a = 0;
675 o2.b = 1;
676 o2.c = 2;
677 o2['strange key'] = 3;
678 </BAD_CODE_SNIPPET>
679 <p>Should be written as:</p>
680 <CODE_SNIPPET>
681 var o = {};
682
683 var o2 = {
684 a: 0,
685 b: 1,
686 c: 2,
687 'strange key': 3
688 };
689 </CODE_SNIPPET>
690 </BODY>
691 </STYLEPOINT>
692
693 <STYLEPOINT title="Modifying prototypes of builtin objects">
694 <SUMMARY>No</SUMMARY>
695 <BODY>
696 <p>Modifying builtins like <code>Object.prototype</code> and
697 <code>Array.prototype</code> are strictly forbidden. Modifying other
698 builtins like <code>Function.prototype</code> is less dangerous but
699 still leads to hard to debug issues in production and should be
700 avoided.</p>
701 </BODY>
702 </STYLEPOINT>
mmentovai7ead6442010-10-04 16:26:53 +0000703
704 <STYLEPOINT title="Internet Explorer's Conditional Comments">
705 <SUMMARY>No</SUMMARY>
706 <BODY>
707 <p>Don't do this:</p>
mmentovaicd4ce0f2011-03-29 20:30:47 +0000708 <BAD_CODE_SNIPPET>
mmentovai7ead6442010-10-04 16:26:53 +0000709 var f = function () {
710 /*@cc_on if (@_jscript) { return 2* @*/ 3; /*@ } @*/
711 };
mmentovaicd4ce0f2011-03-29 20:30:47 +0000712 </BAD_CODE_SNIPPET>
mmentovai7ead6442010-10-04 16:26:53 +0000713 <p>Conditional Comments hinder automated tools as they can vary the
714 JavaScript syntax tree at runtime.</p>
715 </BODY>
716 </STYLEPOINT>
robbyw@google.combb324012010-07-12 22:02:20 +0000717 </CATEGORY>
718
719 <CATEGORY title="JavaScript Style Rules">
720 <STYLEPOINT title="Naming">
721 <SUMMARY>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000722 <p>In general, use
723 <code>functionNamesLikeThis</code>,
724 <code>variableNamesLikeThis</code>,
725 <code>ClassNamesLikeThis</code>,
726 <code>EnumNamesLikeThis</code>,
727 <code>methodNamesLikeThis</code>,
728 <code>CONSTANT_VALUES_LIKE_THIS</code>,
729 <code>foo.namespaceNamesLikeThis.bar</code>, and
730 <code>filenameslikethis.js</code>.
731 </p>
robbyw@google.combb324012010-07-12 22:02:20 +0000732 </SUMMARY>
733 <BODY>
734 <SUBSECTION title="Properties and methods">
735 <ul>
mark@chromium.org8190c132013-03-21 16:03:26 +0000736 <li><em>Private</em> properties and methods should be named with a
737 trailing underscore.
robbyw@google.combb324012010-07-12 22:02:20 +0000738 </li>
mark@chromium.org8190c132013-03-21 16:03:26 +0000739 <li><em>Protected</em> properties and methods should be
robbyw@google.combb324012010-07-12 22:02:20 +0000740 named without a trailing underscore (like public ones).</li>
741 </ul>
742 <p>For more information on <em>private</em> and <em>protected</em>,
743 read the section on
744 <a href="#Visibility__private_and_protected_fields_">
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000745 visibility</a>.
746 </p>
747
748
749
750
robbyw@google.combb324012010-07-12 22:02:20 +0000751 </SUBSECTION>
752
753 <SUBSECTION title="Method and function parameter">
754 <p>Optional function arguments start with <code>opt_</code>.</p>
755 <p>Functions that take a variable number of arguments should have the
756 last argument named <code>var_args</code>. You may not refer to
757 <code>var_args</code> in the code; use the <code>arguments</code>
758 array.</p>
759 <p>Optional and variable arguments can also be specified in
760 <code>@param</code> annotations. Although either convention is
761 acceptable to the compiler, using both together is preferred.</p>
762
763 </SUBSECTION>
764
765 <SUBSECTION title="Getters and Setters">
mark@chromium.orge33361f2011-11-04 16:55:22 +0000766 <p>EcmaScript 5 getters and setters for properties are discouraged.
767 However, if they are used, then getters must not change observable
768 state.</p>
769 <BAD_CODE_SNIPPET>
770 /**
771 * WRONG -- Do NOT do this.
772 */
773 var foo = { get next() { return this.nextId++; } };
mark@chromium.orge33361f2011-11-04 16:55:22 +0000774 </BAD_CODE_SNIPPET>
775 </SUBSECTION>
776
777 <SUBSECTION title="Accessor functions">
778 <p>Getters and setters methods for properties are not required.
779 However, if they are used, then getters must be named
780 <code>getFoo()</code> and setters must be named
781 <code>setFoo(value)</code>. (For boolean getters,
782 <code>isFoo()</code> is also acceptable, and often sounds more
783 natural.)</p>
robbyw@google.combb324012010-07-12 22:02:20 +0000784 </SUBSECTION>
785
786 <SUBSECTION title="Namespaces">
787 <p>JavaScript has no inherent packaging or namespacing support.</p>
788 <p>Global name conflicts are difficult to debug, and can cause
789 intractable problems when two projects try to integrate. In order
790 to make it possible to share common JavaScript code, we've adopted
791 conventions to prevent collisions. </p>
792 <SUBSUBSECTION title="Use namespaces for global code">
793 <p><em>ALWAYS</em> prefix identifiers in the global scope with a
794 unique pseudo namespace related to the project or library. If you
795 are working on "Project Sloth", a reasonable pseudo namespace
796 would be <code>sloth.*</code>.</p>
797 <CODE_SNIPPET>
798 var sloth = {};
799
800 sloth.sleep = function() {
801 ...
802 };
803 </CODE_SNIPPET>
804
805
806 <p>Many JavaScript libraries, including
807 <a href="http://code.google.com/closure/library/">
808 the Closure Library
809 </a>
810 and
811 <a href="http://www.dojotoolkit.org/">
812 Dojo toolkit
813 </a>
814 give you high-level functions for declaring your namespaces.
815 Be consistent about how you declare your namespaces.</p>
816 <CODE_SNIPPET>
817 goog.provide('sloth');
818
819 sloth.sleep = function() {
820 ...
821 };
822 </CODE_SNIPPET>
823 </SUBSUBSECTION>
824 <SUBSUBSECTION title="Respect namespace ownership">
825 <p>When choosing a child-namespace, make sure that the owners of the
826 parent namespace know what you are doing. If you start a project
827 that creates hats for sloths, make sure that the Sloth team knows
828 that you're using <code>sloth.hats</code>.</p>
829
830 </SUBSUBSECTION>
831 <SUBSUBSECTION title="Use different namespaces for external code and internal code">
832 <p>"External code" is code that comes from outside your codebase,
833 and is compiled independently. Internal and external names should
834 be kept strictly separate. If you're using an external library
835 that makes things available in <code>foo.hats.*</code>, your
836 internal code should not define all its symbols in
837 <code>foo.hats.*</code>, because it will break if the other
838 team defines new symbols.</p>
839 <BAD_CODE_SNIPPET>
840 foo.require('foo.hats');
841
842 /**
843 * WRONG -- Do NOT do this.
844 * @constructor
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000845 * @extends {foo.hats.RoundHat}
robbyw@google.combb324012010-07-12 22:02:20 +0000846 */
847 foo.hats.BowlerHat = function() {
848 };
849 </BAD_CODE_SNIPPET>
850 <p>If you need to define new APIs on an external namespace, then you
851 should explicitly export the public API functions, and only those
852 functions. Your internal code should call the internal APIs by
853 their internal names, for consistency and so that the compiler
854 can optimize them better.</p>
855 <CODE_SNIPPET>
856 foo.provide('googleyhats.BowlerHat');
857
858 foo.require('foo.hats');
859
860 /**
861 * @constructor
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000862 * @extends {foo.hats.RoundHat}
robbyw@google.combb324012010-07-12 22:02:20 +0000863 */
864 googleyhats.BowlerHat = function() {
865 ...
866 };
867
868 goog.exportSymbol('foo.hats.BowlerHat', googleyhats.BowlerHat);
869 </CODE_SNIPPET>
870
871
872 </SUBSUBSECTION>
mmentovai7ead6442010-10-04 16:26:53 +0000873 <SUBSUBSECTION title="Alias long type names to improve readability">
874 <p>Use local aliases for fully-qualified types if doing so improves
875 readability. The name of a local alias should match the last part
876 of the type.</p>
877 <CODE_SNIPPET>
878 /**
879 * @constructor
880 */
881 some.long.namespace.MyClass = function() {
882 };
883
884 /**
885 * @param {some.long.namespace.MyClass} a
886 */
887 some.long.namespace.MyClass.staticHelper = function(a) {
888 ...
889 };
890
891 myapp.main = function() {
892 var MyClass = some.long.namespace.MyClass;
893 var staticHelper = some.long.namespace.MyClass.staticHelper;
894 staticHelper(new MyClass());
895 };
896 </CODE_SNIPPET>
mark@chromium.org8190c132013-03-21 16:03:26 +0000897 <p>Do not create local aliases of namespaces. Namespaces should only
898 be aliased using <a href="#goog-scope">goog.scope</a>.</p>
mmentovai7ead6442010-10-04 16:26:53 +0000899 <BAD_CODE_SNIPPET>
900 myapp.main = function() {
901 var namespace = some.long.namespace;
902 namespace.MyClass.staticHelper(new namespace.MyClass());
903 };
904 </BAD_CODE_SNIPPET>
905 <p>Avoid accessing properties of an aliased type, unless it is an
906 enum.</p>
907 <CODE_SNIPPET>
908 /** @enum {string} */
909 some.long.namespace.Fruit = {
910 APPLE: 'a',
911 BANANA: 'b'
912 };
913
914 myapp.main = function() {
915 var Fruit = some.long.namespace.Fruit;
916 switch (fruit) {
917 case Fruit.APPLE:
918 ...
919 case Fruit.BANANA:
920 ...
921 }
922 };
923 </CODE_SNIPPET>
924 <BAD_CODE_SNIPPET>
925 myapp.main = function() {
926 var MyClass = some.long.namespace.MyClass;
927 MyClass.staticHelper(null);
928 };
929 </BAD_CODE_SNIPPET>
930 <p>Never create aliases in the global scope. Use them only in
931 function blocks.</p>
932 </SUBSUBSECTION>
robbyw@google.combb324012010-07-12 22:02:20 +0000933 </SUBSECTION>
934 <SUBSECTION title="Filenames">
935 <p>Filenames should be all lowercase in order to avoid confusion on
936 case-sensitive platforms. Filenames should end in <code>.js</code>,
937 and should contain no punctuation except for <code>-</code> or
938 <code>_</code> (prefer <code>-</code> to <code>_</code>).</p>
939 </SUBSECTION>
940
941 </BODY>
942 </STYLEPOINT>
943
944 <STYLEPOINT title="Custom toString() methods">
945 <SUMMARY>
946 Must always succeed without side effects.
947 </SUMMARY>
948 <BODY>
949 <p>You can control how your objects string-ify themselves by defining a
950 custom <code>toString()</code> method. This is fine, but you need
951 to ensure that your method (1) always succeeds and (2) does not have
952 side-effects. If your method doesn't meet these criteria, it's very
953 easy to run into serious problems. For example, if
954 <code>toString()</code> calls a method that does an
955 <code>assert</code>, <code>assert</code> might try to output the name
956 of the object in which it failed, which of course requires calling
957 <code>toString()</code>.</p>
958 </BODY>
959 </STYLEPOINT>
960
961 <STYLEPOINT title="Deferred initialization">
962 <SUMMARY>OK</SUMMARY>
963 <BODY>
964 <p>It isn't always possible to initialize variables at the point of
965 declaration, so deferred initialization is fine.</p>
966 </BODY>
967 </STYLEPOINT>
968
969 <STYLEPOINT title="Explicit scope">
970 <SUMMARY>Always</SUMMARY>
971 <BODY>
972 <p>Always use explicit scope - doing so increases portability and
973 clarity. For example, don't rely on <code>window</code> being in the
974 scope chain. You might want to use your function in another
975 application for which <code>window</code> is not the content
976 window.</p>
977 </BODY>
978 </STYLEPOINT>
979
980 <STYLEPOINT title="Code formatting">
mmentovaicd4ce0f2011-03-29 20:30:47 +0000981 <SUMMARY>Expand for more information.</SUMMARY>
robbyw@google.combb324012010-07-12 22:02:20 +0000982 <BODY>
983 <p>We follow the <a href="cppguide.xml#Formatting">C++ formatting
984 rules</a> in spirit, with the following additional clarifications.</p>
985 <SUBSECTION title="Curly Braces">
986 <p>Because of implicit semicolon insertion, always start your curly
987 braces on the same line as whatever they're opening. For
988 example:</p>
989 <CODE_SNIPPET>
990 if (something) {
991 // ...
992 } else {
993 // ...
994 }
995 </CODE_SNIPPET>
996 </SUBSECTION>
997 <SUBSECTION title="Array and Object Initializers">
998 <p>Single-line array and object initializers are allowed when they
999 fit on a line:</p>
1000 <CODE_SNIPPET>
1001 var arr = [1, 2, 3]; // No space after [ or before ].
1002 var obj = {a: 1, b: 2, c: 3}; // No space after { or before }.
1003 </CODE_SNIPPET>
1004 <p>Multiline array initializers and object initializers are indented
mark@chromium.org8190c132013-03-21 16:03:26 +00001005 2 spaces, with the braces on their own line, just like blocks.</p>
robbyw@google.combb324012010-07-12 22:02:20 +00001006 <CODE_SNIPPET>
1007 // Object initializer.
1008 var inset = {
1009 top: 10,
1010 right: 20,
1011 bottom: 15,
1012 left: 12
1013 };
1014
1015 // Array initializer.
1016 this.rows_ = [
1017 '"Slartibartfast" &lt;fjordmaster@magrathea.com&gt;',
1018 '"Zaphod Beeblebrox" &lt;theprez@universe.gov&gt;',
1019 '"Ford Prefect" &lt;ford@theguide.com&gt;',
1020 '"Arthur Dent" &lt;has.no.tea@gmail.com&gt;',
1021 '"Marvin the Paranoid Android" &lt;marv@googlemail.com&gt;',
1022 'the.mice@magrathea.com'
1023 ];
1024
1025 // Used in a method call.
1026 goog.dom.createDom(goog.dom.TagName.DIV, {
1027 id: 'foo',
1028 className: 'some-css-class',
1029 style: 'display:none'
1030 }, 'Hello, world!');
1031 </CODE_SNIPPET>
1032 <p>Long identifiers or values present problems for aligned
1033 initialization lists, so always prefer non-aligned initialization.
1034 For example:</p>
1035 <CODE_SNIPPET>
1036 CORRECT_Object.prototype = {
1037 a: 0,
1038 b: 1,
1039 lengthyName: 2
1040 };
1041 </CODE_SNIPPET>
1042 <p>Not like this:</p>
1043 <BAD_CODE_SNIPPET>
1044 WRONG_Object.prototype = {
1045 a : 0,
1046 b : 1,
1047 lengthyName: 2
1048 };
1049 </BAD_CODE_SNIPPET>
1050 </SUBSECTION>
1051 <SUBSECTION title="Function Arguments">
1052 <p>When possible, all function arguments should be listed on the same
1053 line. If doing so would exceed the 80-column limit, the arguments
1054 must be line-wrapped in a readable way. To save space, you may wrap
1055 as close to 80 as possible, or put each argument on its own line to
1056 enhance readability. The indentation may be either four spaces, or
1057 aligned to the parenthesis. Below are the most common patterns for
1058 argument wrapping:</p>
1059 <CODE_SNIPPET>
1060 // Four-space, wrap at 80. Works with very long function names, survives
1061 // renaming without reindenting, low on space.
1062 goog.foo.bar.doThingThatIsVeryDifficultToExplain = function(
1063 veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,
1064 tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {
1065 // ...
1066 };
1067
1068 // Four-space, one argument per line. Works with long function names,
1069 // survives renaming, and emphasizes each argument.
1070 goog.foo.bar.doThingThatIsVeryDifficultToExplain = function(
1071 veryDescriptiveArgumentNumberOne,
1072 veryDescriptiveArgumentTwo,
1073 tableModelEventHandlerProxy,
1074 artichokeDescriptorAdapterIterator) {
1075 // ...
1076 };
1077
1078 // Parenthesis-aligned indentation, wrap at 80. Visually groups arguments,
1079 // low on space.
1080 function foo(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,
1081 tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {
1082 // ...
1083 }
1084
mark@chromium.org7b245632013-09-25 21:16:00 +00001085 // Parenthesis-aligned, one argument per line. Emphasizes each
1086 // individual argument.
robbyw@google.combb324012010-07-12 22:02:20 +00001087 function bar(veryDescriptiveArgumentNumberOne,
1088 veryDescriptiveArgumentTwo,
1089 tableModelEventHandlerProxy,
1090 artichokeDescriptorAdapterIterator) {
1091 // ...
1092 }
1093 </CODE_SNIPPET>
mmentovaicd4ce0f2011-03-29 20:30:47 +00001094 <p>When the function call is itself indented, you're free to start the
1095 4-space indent relative to the beginning of the original statement
1096 or relative to the beginning of the current function call.
1097 The following are all acceptable indentation styles.</p>
1098 <CODE_SNIPPET>
1099 if (veryLongFunctionNameA(
1100 veryLongArgumentName) ||
1101 veryLongFunctionNameB(
1102 veryLongArgumentName)) {
1103 veryLongFunctionNameC(veryLongFunctionNameD(
1104 veryLongFunctioNameE(
1105 veryLongFunctionNameF)));
1106 }
1107 </CODE_SNIPPET>
robbyw@google.combb324012010-07-12 22:02:20 +00001108 </SUBSECTION>
1109 <SUBSECTION title="Passing Anonymous Functions">
1110 <p>When declaring an anonymous function in the list of arguments for
1111 a function call, the body of the function is indented two spaces
mmentovaicd4ce0f2011-03-29 20:30:47 +00001112 from the left edge of the statement, or two spaces from the left
1113 edge of the function keyword. This is to make the body of the
1114 anonymous function easier to read (i.e. not be all squished up into
1115 the right half of the screen).</p>
robbyw@google.combb324012010-07-12 22:02:20 +00001116 <CODE_SNIPPET>
robbyw@google.combb324012010-07-12 22:02:20 +00001117 prefix.something.reallyLongFunctionName('whatever', function(a1, a2) {
1118 if (a1.equals(a2)) {
1119 someOtherLongFunctionName(a1);
1120 } else {
1121 andNowForSomethingCompletelyDifferent(a2.parrot);
1122 }
1123 });
mmentovaicd4ce0f2011-03-29 20:30:47 +00001124
1125 var names = prefix.something.myExcellentMapFunction(
1126 verboselyNamedCollectionOfItems,
1127 function(item) {
1128 return item.name;
1129 });
robbyw@google.combb324012010-07-12 22:02:20 +00001130 </CODE_SNIPPET>
1131 </SUBSECTION>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001132 <SUBSECTION title="Aliasing with goog.scope">
mark@chromium.org8190c132013-03-21 16:03:26 +00001133 <a name="goog-scope"/>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001134 <p>
1135 <a href="https://docs.google.com/document/pub?id=1ETFAuh2kaXMVL-vafUYhaWlhl6b5D9TOvboVg7Zl68Y"><code>goog.scope</code></a>
1136 may be used to shorten references to
1137 namespaced symbols in programs using
1138 <a href="http://code.google.com/closure/library/">the Closure
1139 Library</a>.</p>
1140 <p>Only one <code>goog.scope</code> invocation may be added per
1141 file. Always place it in the global scope.</p>
1142 <p>The opening <code>goog.scope(function() {</code> invocation
1143 must be preceded by exactly one blank line and follow any
1144 <code>goog.provide</code> statements, <code>goog.require</code>
1145 statements, or top-level comments. The invocation must be closed on
1146 the last line in the file. Append <code>// goog.scope</code> to the
1147 closing statement of the scope. Separate the comment from the
1148 semicolon by two spaces.</p>
1149 <p>Similar to C++ namespaces, do not indent under goog.scope
1150 declarations. Instead, continue from the 0 column.</p>
1151 <p>Only alias names that will not be re-assigned to another object
1152 (e.g., most constructors, enums, and namespaces). Do not do
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001153 this (see below for how to alias a constructor):</p>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001154
1155 <BAD_CODE_SNIPPET>
1156 goog.scope(function() {
1157 var Button = goog.ui.Button;
1158
1159 Button = function() { ... };
1160 ...
1161 </BAD_CODE_SNIPPET>
1162
1163 <p>Names must be the same as the last property of the global that they
1164 are aliasing.</p>
1165
1166 <CODE_SNIPPET>
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001167 goog.provide('my.module.SomeType');
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001168
1169 goog.require('goog.dom');
1170 goog.require('goog.ui.Button');
1171
1172 goog.scope(function() {
1173 var Button = goog.ui.Button;
1174 var dom = goog.dom;
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001175
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001176 // Alias new types <b>after</b> the constructor declaration.
1177 my.module.SomeType = function() { ... };
1178 var SomeType = my.module.SomeType;
1179
1180 // Declare methods on the prototype as usual:
1181 SomeType.prototype.findButton = function() {
1182 // Button as aliased above.
1183 this.button = new Button(dom.getElement('my-button'));
1184 };
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001185 ...
1186 }); // goog.scope
1187 </CODE_SNIPPET>
1188 </SUBSECTION>
mark@chromium.org7b245632013-09-25 21:16:00 +00001189 <SUBSECTION title="Indenting wrapped lines">
1190 <p>Except for <a href="#Array_and_Object_literals">array literals,
1191 object literals</a>, and anonymous functions, all wrapped lines
1192 should be indented either left-aligned to a sibling expression
1193 above, or four spaces (not two spaces) deeper than a parent
1194 expression (where "sibling" and "parent" refer to parenthesis
1195 nesting level).
1196 </p>
robbyw@google.combb324012010-07-12 22:02:20 +00001197
1198 <CODE_SNIPPET>
1199 someWonderfulHtml = '<div class="' + getClassesForWonderfulHtml()'">' +
1200 getEvenMoreHtml(someReallyInterestingValues, moreValues,
1201 evenMoreParams, 'a duck', true, 72,
1202 slightlyMoreMonkeys(0xfff)) +
1203 '</div>';
1204
1205 thisIsAVeryLongVariableName =
1206 hereIsAnEvenLongerOtherFunctionNameThatWillNotFitOnPrevLine();
1207
mark@chromium.org7b245632013-09-25 21:16:00 +00001208 thisIsAVeryLongVariableName = siblingOne + siblingTwo + siblingThree +
1209 siblingFour + siblingFive + siblingSix + siblingSeven +
1210 moreSiblingExpressions + allAtTheSameIndentationLevel;
1211
1212 thisIsAVeryLongVariableName = operandOne + operandTwo + operandThree +
1213 operandFour + operandFive * (
1214 aNestedChildExpression + shouldBeIndentedMore);
robbyw@google.combb324012010-07-12 22:02:20 +00001215
1216 someValue = this.foo(
1217 shortArg,
1218 'Some really long string arg - this is a pretty common case, actually.',
1219 shorty2,
1220 this.bar());
1221
1222 if (searchableCollection(allYourStuff).contains(theStuffYouWant) &amp;&amp;
1223 !ambientNotification.isActive() &amp;&amp; (client.isAmbientSupported() ||
erg@google.comf5501162010-10-21 17:20:05 +00001224 client.alwaysTryAmbientAnyways())) {
robbyw@google.combb324012010-07-12 22:02:20 +00001225 ambientNotification.activate();
1226 }
1227 </CODE_SNIPPET>
1228 </SUBSECTION>
1229 <SUBSECTION title="Blank lines">
1230 <p>Use newlines to group logically related pieces of code.
1231 For example:</p>
1232 <CODE_SNIPPET>
1233 doSomethingTo(x);
1234 doSomethingElseTo(x);
1235 andThen(x);
1236
1237 nowDoSomethingWith(y);
1238
1239 andNowWith(z);
1240 </CODE_SNIPPET>
1241 </SUBSECTION>
1242 <SUBSECTION title="Binary and Ternary Operators">
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001243 <p>Always put the operator on the preceding line. Otherwise,
robbyw@google.combb324012010-07-12 22:02:20 +00001244 line breaks and indentation follow the same rules as in other
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001245 Google style guides. This operator placement was initially agreed
1246 upon out of concerns about automatic semicolon insertion. In fact,
1247 semicolon insertion cannot happen before a binary operator, but new
1248 code should stick to this style for consistency.</p>
robbyw@google.combb324012010-07-12 22:02:20 +00001249 <CODE_SNIPPET>
1250 var x = a ? b : c; // All on one line if it will fit.
1251
1252 // Indentation +4 is OK.
1253 var y = a ?
1254 longButSimpleOperandB : longButSimpleOperandC;
1255
1256 // Indenting to the line position of the first operand is also OK.
1257 var z = a ?
1258 moreComplicatedB :
1259 moreComplicatedC;
1260 </CODE_SNIPPET>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001261 <p>This includes the dot operator.</p>
1262 <CODE_SNIPPET>
1263 var x = foo.bar().
1264 doSomething().
1265 doSomethingElse();
1266 </CODE_SNIPPET>
robbyw@google.combb324012010-07-12 22:02:20 +00001267 </SUBSECTION>
1268 </BODY>
1269 </STYLEPOINT>
1270
1271 <STYLEPOINT title="Parentheses">
1272 <SUMMARY>Only where required</SUMMARY>
1273 <BODY>
1274 <p>Use sparingly and in general only where required by the syntax
1275 and semantics.</p>
1276 <p>Never use parentheses for unary operators such as
1277 <code>delete</code>, <code>typeof</code> and <code>void</code> or
1278 after keywords such as <code>return</code>, <code>throw</code> as
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001279 well as others (<code>case</code>, <code>in</code> or
1280 <code>new</code>).</p>
robbyw@google.combb324012010-07-12 22:02:20 +00001281 </BODY>
1282 </STYLEPOINT>
1283
1284 <STYLEPOINT title="Strings">
1285 <SUMMARY>Prefer ' over "</SUMMARY>
1286 <BODY>
1287 <p>For consistency single-quotes (') are preferred to double-quotes (").
1288 This is helpful when creating strings that include HTML:</p>
1289 <CODE_SNIPPET>
1290 var msg = 'This is <a href="http://foo">some HTML</a>';
1291 </CODE_SNIPPET>
1292 </BODY>
1293 </STYLEPOINT>
1294
1295 <STYLEPOINT title="Visibility (private and protected fields)">
1296 <SUMMARY>Encouraged, use JSDoc annotations <code>@private</code> and
1297 <code>@protected</code></SUMMARY>
1298 <BODY>
1299 <p>We recommend the use of the JSDoc annotations <code>@private</code> and
1300 <code>@protected</code> to indicate visibility levels for classes,
1301 functions, and properties.</p>
mmentovaicd4ce0f2011-03-29 20:30:47 +00001302 <p>The --jscomp_warning=visibility compiler flag turns on compiler
1303 warnings for visibility violations. See
1304 <a href="http://code.google.com/p/closure-compiler/wiki/Warnings">
1305 Closure Compiler
1306 Warnings</a>.
1307 </p>
robbyw@google.combb324012010-07-12 22:02:20 +00001308 <p><code>@private</code> global variables and functions are only
1309 accessible to code in the same file.</p>
1310 <p>Constructors marked <code>@private</code> may only be instantiated by
1311 code in the same file and by their static and instance members.
1312 <code>@private</code> constructors may also be accessed anywhere in the
1313 same file for their public static properties and by the
1314 <code>instanceof</code> operator.</p>
1315 <p>Global variables, functions, and constructors should never be
1316 annotated <code>@protected</code>.</p>
1317 <CODE_SNIPPET>
1318 // File 1.
1319 // AA_PrivateClass_ and AA_init_ are accessible because they are global
1320 // and in the same file.
1321
1322 /**
1323 * @private
1324 * @constructor
1325 */
1326 AA_PrivateClass_ = function() {
1327 };
1328
1329 /** @private */
1330 function AA_init_() {
1331 return new AA_PrivateClass_();
1332 }
1333
1334 AA_init_();
1335 </CODE_SNIPPET>
1336 <p><code>@private</code> properties are accessible to all code in the
1337 same file, plus all static methods and instance methods of that class
mmentovaib2ad0102010-08-04 17:43:38 +00001338 that "owns" the property, if the property belongs to a class. They
1339 cannot be accessed or overridden from a subclass in a different file.</p>
robbyw@google.combb324012010-07-12 22:02:20 +00001340 <p><code>@protected</code> properties are accessible to all code in the
1341 same file, plus any static methods and instance methods of any subclass
1342 of a class that "owns" the property.</p>
mmentovaib2ad0102010-08-04 17:43:38 +00001343 <p>Note that these semantics differ from those of C++ and Java, in that
1344 they grant private and protected access to all code in the same file,
1345 not just in the same class or class hierarchy. Also, unlike in C++,
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001346 private properties cannot be overridden by a subclass.
mmentovaib2ad0102010-08-04 17:43:38 +00001347 </p>
robbyw@google.combb324012010-07-12 22:02:20 +00001348 <CODE_SNIPPET>
1349 // File 1.
1350
1351 /** @constructor */
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001352 AA_PublicClass = function() {
1353 /** @private */
1354 this.privateProp_ = 2;
1355
1356 /** @protected */
1357 this.protectedProp = 4;
robbyw@google.combb324012010-07-12 22:02:20 +00001358 };
1359
1360 /** @private */
1361 AA_PublicClass.staticPrivateProp_ = 1;
1362
robbyw@google.combb324012010-07-12 22:02:20 +00001363 /** @protected */
1364 AA_PublicClass.staticProtectedProp = 31;
1365
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001366 /** @private */
1367 AA_PublicClass.prototype.privateMethod_ = function() {};
1368
robbyw@google.combb324012010-07-12 22:02:20 +00001369 /** @protected */
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001370 AA_PublicClass.prototype.protectedMethod = function() {};
robbyw@google.combb324012010-07-12 22:02:20 +00001371
1372 // File 2.
1373
1374 /**
1375 * @return {number} The number of ducks we've arranged in a row.
1376 */
1377 AA_PublicClass.prototype.method = function() {
1378 // Legal accesses of these two properties.
1379 return this.privateProp_ + AA_PublicClass.staticPrivateProp_;
1380 };
1381
1382 // File 3.
1383
1384 /**
1385 * @constructor
1386 * @extends {AA_PublicClass}
1387 */
1388 AA_SubClass = function() {
1389 // Legal access of a protected static property.
1390 AA_PublicClass.staticProtectedProp = this.method();
1391 };
1392 goog.inherits(AA_SubClass, AA_PublicClass);
1393
1394 /**
1395 * @return {number} The number of ducks we've arranged in a row.
1396 */
1397 AA_SubClass.prototype.method = function() {
1398 // Legal access of a protected instance property.
1399 return this.protectedProp;
1400 };
1401 </CODE_SNIPPET>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001402
1403 <p>Notice that in JavaScript, there is no distinction between a type
1404 (like <code>AA_PrivateClass_</code>) and the constructor for that
1405 type. There is no way to express both that a type is public and its
1406 constructor is private (because the constructor could easily be aliased
1407 in a way that would defeat the privacy check).</p>
robbyw@google.combb324012010-07-12 22:02:20 +00001408 </BODY>
1409 </STYLEPOINT>
1410
1411 <STYLEPOINT title="JavaScript Types">
1412 <SUMMARY>Encouraged and enforced by the compiler.</SUMMARY>
1413 <BODY>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001414 <a name="JsTypes"/>
robbyw@google.combb324012010-07-12 22:02:20 +00001415 <p>When documenting a type in JSDoc, be as specific and accurate as
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001416 possible. The types we support are based on the
robbyw@google.combb324012010-07-12 22:02:20 +00001417 <a href="http://wiki.ecmascript.org/doku.php?id=spec:spec">
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001418 EcmaScript 4 spec</a>.</p>
robbyw@google.combb324012010-07-12 22:02:20 +00001419 <SUBSECTION title="The JavaScript Type Language">
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001420 <p>The ES4 proposal contained a language for specifying JavaScript
robbyw@google.combb324012010-07-12 22:02:20 +00001421 types. We use this language in JsDoc to express the types of
1422 function parameters and return values.</p>
1423
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001424 <p>As the ES4 proposal has evolved, this language has changed. The
robbyw@google.combb324012010-07-12 22:02:20 +00001425 compiler still supports old syntaxes for types, but those syntaxes
1426 are deprecated.</p>
1427
mark@chromium.orge33361f2011-11-04 16:55:22 +00001428 <p/>
robbyw@google.combb324012010-07-12 22:02:20 +00001429 <table border="1" style="border-collapse:collapse" cellpadding="4">
1430 <thead>
1431 <tr>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001432 <th>Syntax Name</th>
robbyw@google.combb324012010-07-12 22:02:20 +00001433 <th>Syntax</th>
1434 <th>Description</th>
1435 <th>Deprecated Syntaxes</th>
1436 </tr>
1437 </thead>
1438 <tbody>
1439 <tr>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001440 <td>Primitive Type</td>
robbyw@google.combb324012010-07-12 22:02:20 +00001441 <td>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001442 There are 5 primitive types in JavaScript:
1443 <code>{null}</code>,
1444 <code>{undefined}</code>,
1445 <code>{boolean}</code>,
1446 <code>{number}</code>, and
1447 <code>{string}</code>.
robbyw@google.combb324012010-07-12 22:02:20 +00001448 </td>
1449 <td>Simply the name of a type.</td>
1450 <td/>
1451 </tr>
1452
1453 <tr>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001454 <td>Instance Type</td>
1455 <td>
1456 <code>{Object}</code><br/>
1457 An instance of Object or null.<p/>
1458 <code>{Function}</code><br/>
1459 An instance of Function or null.<p/>
1460 <code>{EventTarget}</code><br/>
1461 An instance of a constructor that implements the EventTarget
1462 interface, or null.
1463 </td>
1464 <td>An instance of a constructor or interface function.<p/>
1465
1466 Constructor functions are functions defined with the
1467 <code>@constructor</code> JSDoc tag.
1468 Interface functions are functions defined with the
1469 <code>@interface</code> JSDoc tag.<p/>
1470
1471 By default, instance types will accept null. This is the only
1472 type syntax that makes the type nullable. Other type syntaxes
1473 in this table will not accept null.
1474 </td>
1475 <td/>
1476 </tr>
1477
1478 <tr>
1479 <td>Enum Type</td>
1480 <td>
1481 <code>{goog.events.EventType}</code><br/>
1482 One of the properties of the object literal initializer
1483 of <code>goog.events.EventType</code>.
1484 </td>
1485 <td>An enum must be initialized as an object literal, or as
1486 an alias of another enum, annotated with the <code>@enum</code>
1487 JSDoc tag. The properties of this literal are the instances
1488 of the enum. The syntax of the enum is defined
1489 <a href="#enums">below</a>.<p/>
1490
1491 Note that this is one of the few things in our type system
1492 that were not in the ES4 spec.
1493 </td>
1494 <td/>
1495 </tr>
1496
1497 <tr>
robbyw@google.combb324012010-07-12 22:02:20 +00001498 <td>Type Application</td>
1499 <td>
1500 <code>{Array.&lt;string&gt;}</code><br/>An array of strings.<p/>
1501 <code>{Object.&lt;string, number&gt;}</code>
1502 <br/>An object in which the keys are strings and the values
1503 are numbers.
1504 </td>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001505 <td>Parameterizes a type, by applying a set of type arguments
robbyw@google.combb324012010-07-12 22:02:20 +00001506 to that type. The idea is analogous to generics in Java.
1507 </td>
1508 <td/>
1509 </tr>
1510
1511 <tr>
1512 <td>Type Union</td>
1513 <td>
1514 <code>{(number|boolean)}</code><br/>A number or a boolean.
1515 </td>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001516 <td>Indicates that a value might have type A OR type B.<p/>
1517
1518 The parentheses may be omitted at the top-level
1519 expression, but the parentheses should be included in
1520 sub-expressions to avoid ambiguity.<br/>
1521 <code>{number|boolean}</code><br/>
1522 <code>{function(): (number|boolean)}</code>
1523 </td>
robbyw@google.combb324012010-07-12 22:02:20 +00001524 <td>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001525 <code>{(number,boolean)}</code>,<br/>
robbyw@google.combb324012010-07-12 22:02:20 +00001526 <code>{(number||boolean)}</code>
1527 </td>
1528 </tr>
1529
1530 <tr>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001531 <td>Nullable type</td>
1532 <td>
1533 <code>{?number}</code><br/> A number or null.
1534 </td>
1535 <td>Shorthand for the union of the null type with any
1536 other type. This is just syntactic sugar.
1537 </td>
1538 <td>
1539 <code>{number?}</code>
1540 </td>
1541 </tr>
1542
1543 <tr>
1544 <td>Non-nullable type</td>
1545 <td>
1546 <code>{!Object}</code><br/> An Object, but never the
1547 <code>null</code> value.
1548 </td>
1549 <td>Filters null out of nullable types. Most often used
1550 with instance types, which are nullable by default.
1551 </td>
1552 <td>
1553 <code>{Object!}</code>
1554 </td>
1555 </tr>
1556
1557 <tr>
robbyw@google.combb324012010-07-12 22:02:20 +00001558 <td>Record Type</td>
1559 <td>
1560 <code>{{myNum: number, myObject}}</code>
1561 <br/>An anonymous type with the given type members.
1562 </td>
1563 <td>
1564 <p>Indicates that the value has the specified members with the
1565 specified types. In this case, <code>myNum</code> with a
1566 type <code>number</code> and <code>myObject</code> with any
1567 type.</p>
1568 <p>Notice that the braces are part of the type syntax. For
1569 example, to denote an <code>Array</code> of objects that
1570 have a <code>length</code> property, you might write
1571 <code>Array.&lt;{length}&gt;</code>.</p>
1572 </td>
1573 <td/>
1574 </tr>
1575
1576 <tr>
robbyw@google.combb324012010-07-12 22:02:20 +00001577 <td>Function Type</td>
1578 <td>
1579 <code>{function(string, boolean)}</code><br/>
1580 A function that takes two arguments (a string and a boolean),
1581 and has an unknown return value.<br/>
1582 </td>
1583 <td>Specifies a function.</td>
1584 <td/>
1585 </tr>
1586
1587 <tr>
1588 <td>Function Return Type</td>
1589 <td>
1590 <code>{function(): number}</code><br/>
1591 A function that takes no arguments and returns a number.<br/>
1592 </td>
1593 <td>Specifies a function return type.</td>
1594 <td/>
1595 </tr>
1596
1597 <tr>
1598 <td>Function <code>this</code> Type</td>
1599 <td>
1600 <code>{function(this:goog.ui.Menu, string)}</code><br/>
1601 A function that takes one argument (a string), and executes
1602 in the context of a goog.ui.Menu.
1603 </td>
1604 <td>Specifies the context type of a function type.</td>
1605 <td/>
1606 </tr>
1607
1608 <tr>
mmentovaicd4ce0f2011-03-29 20:30:47 +00001609 <td>Function <code>new</code> Type</td>
1610 <td>
1611 <code>{function(new:goog.ui.Menu, string)}</code><br/>
1612 A constructor that takes one argument (a string), and
1613 creates a new instance of goog.ui.Menu when called
1614 with the 'new' keyword.
1615 </td>
1616 <td>Specifies the constructed type of a constructor.</td>
1617 <td/>
1618 </tr>
1619
1620 <tr>
robbyw@google.combb324012010-07-12 22:02:20 +00001621 <td>Variable arguments</td>
1622 <td>
1623 <code>{function(string, ...[number]): number}</code><br/>
1624 A function that takes one argument (a string), and then a
1625 variable number of arguments that must be numbers.
1626 </td>
1627 <td>Specifies variable arguments to a function.</td>
1628 <td/>
1629 </tr>
1630
1631 <tr>
1632 <td>
1633 <a name="var-args-annotation"/>
1634 Variable arguments (in <code>@param</code> annotations)
1635 </td>
1636 <td>
1637 <code>@param {...number} var_args</code><br/>
1638 A variable number of arguments to an annotated function.
1639 </td>
1640 <td>
1641 Specifies that the annotated function accepts a variable
1642 number of arguments.
1643 </td>
1644 <td/>
1645 </tr>
1646
1647 <tr>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001648 <td>Function <a href="#optional">optional arguments</a></td>
robbyw@google.combb324012010-07-12 22:02:20 +00001649 <td>
1650 <code>{function(?string=, number=)}</code><br/>
1651 A function that takes one optional, nullable string and one
1652 optional number as arguments. The <code>=</code> syntax is
1653 only for <code>function</code> type declarations.
1654 </td>
1655 <td>Specifies optional arguments to a function.</td>
1656 <td/>
1657 </tr>
1658
1659 <tr>
1660 <td>
1661 <a name="optional-arg-annotation"/>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001662 Function <a href="#optional">optional arguments</a>
robbyw@google.combb324012010-07-12 22:02:20 +00001663 (in <code>@param</code> annotations)
1664 </td>
1665 <td>
1666 <code>@param {number=} opt_argument</code><br/>
1667 An optional parameter of type <code>number</code>.
1668 </td>
1669 <td>Specifies that the annotated function accepts an optional
1670 argument.</td>
1671 <td/>
1672 </tr>
1673
1674 <tr>
1675 <td>The ALL type</td>
1676 <td><code>{*}</code></td>
1677 <td>Indicates that the variable can take on any type.</td>
1678 <td/>
1679 </tr>
mmentovaicd4ce0f2011-03-29 20:30:47 +00001680
1681 <tr>
1682 <td>The UNKNOWN type</td>
1683 <td><code>{?}</code></td>
1684 <td>Indicates that the variable can take on any type,
1685 and the compiler should not type-check any uses of it.</td>
1686 <td/>
1687 </tr>
robbyw@google.combb324012010-07-12 22:02:20 +00001688 </tbody>
1689 </table>
1690 </SUBSECTION>
1691 <SUBSECTION title="Types in JavaScript">
1692 <p/>
1693 <table border="1" style="border-collapse:collapse" cellpadding="4">
1694 <thead>
1695 <tr>
1696 <th>Type Example</th>
1697 <th>Value Examples</th>
1698 <th>Description</th>
1699 </tr>
1700 </thead>
1701 <tbody>
1702
1703 <tr>
1704 <td>number</td>
1705 <td>
1706 <CODE_SNIPPET>
1707 1
1708 1.0
1709 -5
1710 1e5
1711 Math.PI
1712 </CODE_SNIPPET>
1713 </td>
1714 <td/>
1715 </tr>
1716
1717 <tr>
1718 <td>Number</td>
1719 <td>
1720 <CODE_SNIPPET>
1721 new Number(true)
1722 </CODE_SNIPPET>
1723 </td>
1724 <td>
1725 <a href="#Wrapper_objects_for_primitive_types">
1726 Number object
1727 </a>
1728 </td>
1729 </tr>
1730
1731 <tr>
1732 <td>string</td>
1733 <td>
1734 <CODE_SNIPPET>
1735 'Hello'
1736 "World"
1737 String(42)
1738 </CODE_SNIPPET>
1739 </td>
1740 <td>
1741 String value
1742 </td>
1743 </tr>
1744
1745 <tr>
1746 <td>String</td>
1747 <td>
1748 <CODE_SNIPPET>
1749 new String('Hello')
1750 new String(42)
1751 </CODE_SNIPPET>
1752 </td>
1753 <td>
1754 <a href="#Wrapper_objects_for_primitive_types">
1755 String object
1756 </a>
1757 </td>
1758 </tr>
1759
1760 <tr>
1761 <td>boolean</td>
1762 <td>
1763 <CODE_SNIPPET>
1764 true
1765 false
1766 Boolean(0)
1767 </CODE_SNIPPET>
1768 </td>
1769 <td>
1770 Boolean value
1771 </td>
1772 </tr>
1773
1774 <tr>
1775 <td>Boolean</td>
1776 <td>
1777 <CODE_SNIPPET>
1778 new Boolean(true)
1779 </CODE_SNIPPET>
1780 </td>
1781 <td>
1782 <a href="#Wrapper_objects_for_primitive_types">
1783 Boolean object
1784 </a>
1785 </td>
1786 </tr>
1787
1788 <tr>
1789 <td>RegExp</td>
1790 <td>
1791 <CODE_SNIPPET>
1792 new RegExp('hello')
1793 /world/g
1794 </CODE_SNIPPET></td><td>
1795 </td>
1796 </tr>
1797
1798 <tr>
1799 <td>Date</td>
1800 <td>
1801 <CODE_SNIPPET>
1802 new Date
1803 new Date()
1804 </CODE_SNIPPET></td>
1805 <td/>
1806 </tr>
1807
1808 <tr>
1809 <td>
1810
1811 null
1812
1813 </td>
1814 <td>
1815 <CODE_SNIPPET>
1816 null
1817 </CODE_SNIPPET>
1818 </td>
1819 <td/>
1820 </tr>
1821
1822 <tr>
1823 <td>
1824
1825 undefined
1826
1827 </td>
1828 <td>
1829 <CODE_SNIPPET>
1830 undefined
1831 </CODE_SNIPPET>
1832 </td>
1833 <td/>
1834 </tr>
1835
1836 <tr>
1837 <td>void</td>
1838 <td>
1839 <CODE_SNIPPET>
1840 function f() {
1841 return;
1842 }
1843 </CODE_SNIPPET>
1844 </td>
1845 <td>No return value</td>
1846 </tr>
1847
1848 <tr>
1849 <td>Array</td>
1850 <td>
1851 <CODE_SNIPPET>
1852 ['foo', 0.3, null]
1853 []
1854 </CODE_SNIPPET>
1855 </td>
1856 <td>Untyped Array</td>
1857 </tr>
1858
1859 <tr>
1860 <td>Array.&lt;number&gt;</td>
1861 <td>
1862 <CODE_SNIPPET>
1863 [11, 22, 33]
1864 </CODE_SNIPPET>
1865 </td>
1866 <td>
1867 An Array of numbers
1868 </td>
1869 </tr>
1870
1871 <tr>
1872 <td>Array.&lt;Array.&lt;string&gt;&gt;</td>
1873 <td>
1874 <CODE_SNIPPET>
1875 [['one', 'two', 'three'], ['foo', 'bar']]
1876 </CODE_SNIPPET>
1877 </td>
1878 <td>Array of Arrays of strings</td>
1879 </tr>
1880
1881 <tr>
1882 <td>Object</td>
1883 <td>
1884 <CODE_SNIPPET>
1885 {}
1886 {foo: 'abc', bar: 123, baz: null}
1887 </CODE_SNIPPET>
1888 </td>
1889 <td/>
1890 </tr>
1891
1892 <tr>
1893 <td>Object.&lt;string&gt;</td>
1894 <td>
1895 <CODE_SNIPPET>
1896 {'foo': 'bar'}
1897 </CODE_SNIPPET>
1898 </td>
1899 <td>
1900 An Object in which the values are strings.
1901 </td>
1902 </tr>
1903
1904 <tr>
1905 <td>Object.&lt;number, string&gt;</td>
1906 <td>
1907 <CODE_SNIPPET>
1908 var obj = {};
1909 obj[1] = 'bar';
1910 </CODE_SNIPPET>
1911 </td>
1912 <td>
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001913 An Object in which the keys are numbers and the values are
1914 strings. <p/>Note that in JavaScript, the keys are always
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001915 implicitly converted to strings, so
robbyw@google.combb324012010-07-12 22:02:20 +00001916 <code>obj['1'] == obj[1]</code>.
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001917 So the key will always be a string in for...in loops. But the
1918 compiler will verify the type of the key when indexing into
robbyw@google.combb324012010-07-12 22:02:20 +00001919 the object.
1920 </td>
1921 </tr>
1922
1923 <tr>
1924 <td>Function</td>
1925 <td>
1926 <CODE_SNIPPET>
1927 function(x, y) {
1928 return x * y;
1929 }
1930 </CODE_SNIPPET>
1931 </td>
1932 <td>
1933 <a href="#Wrapper_objects_for_primitive_types">
1934 Function object
1935 </a>
1936 </td>
1937 </tr>
1938
1939 <tr>
1940 <td>function(number, number): number</td>
1941 <td>
1942 <CODE_SNIPPET>
1943 function(x, y) {
1944 return x * y;
1945 }
1946 </CODE_SNIPPET>
1947 </td>
1948 <td>function value</td>
1949 </tr>
1950
1951 <tr>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001952 <td><a name="constructor-tag">SomeClass</a></td>
robbyw@google.combb324012010-07-12 22:02:20 +00001953 <td>
1954 <CODE_SNIPPET>
1955 /** @constructor */
1956 function SomeClass() {}
1957
1958 new SomeClass();
1959 </CODE_SNIPPET>
1960 </td>
1961 <td/>
1962 </tr>
1963
1964 <tr>
1965 <td>SomeInterface</td>
1966 <td>
1967 <CODE_SNIPPET>
1968 /** @interface */
1969 function SomeInterface() {}
1970
1971 SomeInterface.prototype.draw = function() {};
1972 </CODE_SNIPPET>
1973 </td>
1974 <td/>
1975 </tr>
1976
1977 <tr>
1978 <td>project.MyClass</td>
1979 <td>
1980 <CODE_SNIPPET>
1981 /** @constructor */
1982 project.MyClass = function () {}
1983
1984 new project.MyClass()
1985 </CODE_SNIPPET>
1986 </td>
1987 <td/>
1988 </tr>
1989
1990 <tr>
1991 <td>project.MyEnum</td>
1992 <td>
1993 <CODE_SNIPPET>
1994 /** @enum {string} */
1995 project.MyEnum = {
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001996 /** The color blue. */
robbyw@google.combb324012010-07-12 22:02:20 +00001997 BLUE: '#0000dd',
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001998 /** The color red. */
robbyw@google.combb324012010-07-12 22:02:20 +00001999 RED: '#dd0000'
2000 };
2001 </CODE_SNIPPET>
2002 </td>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002003 <td><a name="enums">Enumeration</a><p/>
2004 JSDoc comments on enum values are optional.
2005 </td>
robbyw@google.combb324012010-07-12 22:02:20 +00002006 </tr>
2007
2008 <tr>
2009 <td>Element</td>
2010 <td>
2011 <CODE_SNIPPET>
2012 document.createElement('div')
2013 </CODE_SNIPPET>
2014 </td>
2015 <td>Elements in the DOM.</td>
2016 </tr>
2017
2018 <tr>
2019 <td>Node</td>
2020 <td>
2021 <CODE_SNIPPET>
2022 document.body.firstChild
2023 </CODE_SNIPPET>
2024 </td>
2025 <td>Nodes in the DOM.</td>
2026 </tr>
2027
2028 <tr>
2029 <td>HTMLInputElement</td>
2030 <td>
2031 <CODE_SNIPPET>
2032 htmlDocument.getElementsByTagName('input')[0]
2033 </CODE_SNIPPET>
2034 </td>
2035 <td>A specific type of DOM element.</td>
2036 </tr>
2037 </tbody>
2038 </table>
2039 </SUBSECTION>
2040
mark@chromium.orge33361f2011-11-04 16:55:22 +00002041 <SUBSECTION title="Type Casts">
2042 <p>In cases where type-checking doesn't accurately infer the type of
2043 an expression, it is possible to add a type cast comment by adding a
2044 type annotation comment and enclosing the expression in
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002045 parentheses. The parentheses are required.</p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002046
2047 <CODE_SNIPPET>
2048 /** @type {number} */ (x)
mark@chromium.orge33361f2011-11-04 16:55:22 +00002049 </CODE_SNIPPET>
2050 </SUBSECTION>
2051
robbyw@google.combb324012010-07-12 22:02:20 +00002052 <SUBSECTION title="Nullable vs. Optional Parameters and Properties">
2053 <a name="optional"/>
2054 <p>Because JavaScript is a loosely-typed language, it is very
2055 important to understand the subtle differences between optional,
2056 nullable, and undefined function parameters and class
2057 properties.</p>
2058
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002059 <p>Instances of classes and interfaces are nullable by default.
2060 For example, the following declaration</p>
robbyw@google.combb324012010-07-12 22:02:20 +00002061
2062 <CODE_SNIPPET>
2063 /**
2064 * Some class, initialized with a value.
2065 * @param {Object} value Some value.
2066 * @constructor
2067 */
2068 function MyClass(value) {
2069 /**
2070 * Some value.
2071 * @type {Object}
2072 * @private
2073 */
2074 this.myValue_ = value;
2075 }
2076 </CODE_SNIPPET>
2077
2078 <p>tells the compiler that the <code>myValue_</code> property holds
2079 either an Object or null. If <code>myValue_</code> must never be
2080 null, it should be declared like this:</p>
2081
2082 <CODE_SNIPPET>
2083 /**
2084 * Some class, initialized with a non-null value.
2085 * @param {!Object} value Some value.
2086 * @constructor
2087 */
2088 function MyClass(value) {
2089 /**
2090 * Some value.
2091 * @type {!Object}
2092 * @private
2093 */
2094 this.myValue_ = value;
2095 }
2096 </CODE_SNIPPET>
2097
2098 <p>This way, if the compiler can determine that somewhere in the code
2099 <code>MyClass</code> is initialized with a null value, it will issue
2100 a warning.</p>
2101
2102
2103
2104 <p>Optional parameters to functions may be undefined at runtime, so if
2105 they are assigned to class properties, those properties must be
2106 declared accordingly:</p>
2107
2108 <CODE_SNIPPET>
2109 /**
2110 * Some class, initialized with an optional value.
2111 * @param {Object=} opt_value Some value (optional).
2112 * @constructor
2113 */
2114 function MyClass(opt_value) {
2115 /**
2116 * Some value.
2117 * @type {Object|undefined}
2118 * @private
2119 */
2120 this.myValue_ = opt_value;
2121 }
2122 </CODE_SNIPPET>
2123
2124 <p>This tells the compiler that <code>myValue_</code> may hold an
2125 Object, null, or remain undefined.</p>
2126
2127 <p>Note that the optional parameter <code>opt_value</code> is declared
2128 to be of type <code>{Object=}</code>, not
2129 <code>{Object|undefined}</code>. This is because optional
2130 parameters may, by definition, be undefined. While there is no harm
2131 in explicitly declaring an optional parameter as possibly undefined,
2132 it is both unnecessary and makes the code harder to read.</p>
2133
2134 <p>Finally, note that being nullable and being optional are orthogonal
2135 properties. The following four declarations are all different:</p>
2136
2137 <CODE_SNIPPET>
2138 /**
2139 * Takes four arguments, two of which are nullable, and two of which are
2140 * optional.
2141 * @param {!Object} nonNull Mandatory (must not be undefined), must not be null.
2142 * @param {Object} mayBeNull Mandatory (must not be undefined), may be null.
2143 * @param {!Object=} opt_nonNull Optional (may be undefined), but if present,
2144 * must not be null!
2145 * @param {Object=} opt_mayBeNull Optional (may be undefined), may be null.
2146 */
2147 function strangeButTrue(nonNull, mayBeNull, opt_nonNull, opt_mayBeNull) {
2148 // ...
2149 };
2150 </CODE_SNIPPET>
2151 </SUBSECTION>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002152
2153 <SUBSECTION title="Typedefs">
2154 <a name="Typedefs"/>
2155 <p>Sometimes types can get complicated. A function that accepts
2156 content for an Element might look like:</p>
2157
2158 <CODE_SNIPPET>
2159 /**
2160 * @param {string} tagName
2161 * @param {(string|Element|Text|Array.&lt;Element&gt;|Array.&lt;Text&gt;)} contents
2162 * @return {!Element}
2163 */
2164 goog.createElement = function(tagName, contents) {
2165 ...
2166 };
2167 </CODE_SNIPPET>
2168
2169 <p>You can define commonly used type expressions with a
2170 <code>@typedef</code> tag. For example,</p>
2171
2172 <CODE_SNIPPET>
2173 /** @typedef {(string|Element|Text|Array.&lt;Element&gt;|Array.&lt;Text&gt;)} */
2174 goog.ElementContent;
2175
2176 /**
2177 * @param {string} tagName
2178 * @param {goog.ElementContent} contents
2179 * @return {!Element}
2180 */
2181 goog.createElement = function(tagName, contents) {
2182 ...
2183 };
2184 </CODE_SNIPPET>
2185 </SUBSECTION>
2186
2187 <SUBSECTION title="Template types">
2188 <a name="Template_types"/>
2189 <p>The compiler has limited support for template types. It can only
2190 infer the type of <code>this</code> inside an anonymous function
2191 literal from the type of the <code>this</code> argument and whether the
2192 <code>this</code> argument is missing.</p>
2193
2194 <CODE_SNIPPET>
2195 /**
2196 * @param {function(this:T, ...)} fn
2197 * @param {T} thisObj
2198 * @param {...*} var_args
2199 * @template T
2200 */
2201 goog.bind = function(fn, thisObj, var_args) {
2202 ...
2203 };
2204 // Possibly generates a missing property warning.
2205 goog.bind(function() { this.someProperty; }, new SomeClass());
2206 // Generates an undefined this warning.
2207 goog.bind(function() { this.someProperty; });
2208 </CODE_SNIPPET>
2209 </SUBSECTION>
robbyw@google.combb324012010-07-12 22:02:20 +00002210 </BODY>
2211 </STYLEPOINT>
2212
2213 <STYLEPOINT title="Comments">
2214 <SUMMARY>Use JSDoc</SUMMARY>
2215 <BODY>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002216 <p>
2217 We follow the
robbyw@google.combb324012010-07-12 22:02:20 +00002218 <a href="cppguide.xml#Comments">
mark@chromium.org7b245632013-09-25 21:16:00 +00002219 C++ style for comments</a> in spirit.
robbyw@google.combb324012010-07-12 22:02:20 +00002220 </p>
robbyw@google.combb324012010-07-12 22:02:20 +00002221
mark@chromium.orge33361f2011-11-04 16:55:22 +00002222 <p>All files, classes, methods and properties should be documented with
2223 <a href="http://code.google.com/p/jsdoc-toolkit/">JSDoc</a>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002224 comments with the appropriate <a href="#JSDoc_Tag_Reference">tags</a>
mark@chromium.org5684bbc2013-07-12 18:53:13 +00002225 and <a href="#JsTypes">types</a>. Textual descriptions for properties,
2226 methods, method parameters and method return values should be included
2227 unless obvious from the property, method, or parameter name.
mark@chromium.org8190c132013-03-21 16:03:26 +00002228 </p>
robbyw@google.combb324012010-07-12 22:02:20 +00002229
mark@chromium.orge33361f2011-11-04 16:55:22 +00002230 <p>Inline comments should be of the <code>//</code> variety.</p>
robbyw@google.combb324012010-07-12 22:02:20 +00002231
mark@chromium.org5684bbc2013-07-12 18:53:13 +00002232 <p>Complete sentences are recommended but not required.
2233 Complete sentences should use appropriate capitalization
2234 and punctuation.</p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002235
2236 <SUBSECTION title="Comment Syntax">
2237 <p>The JSDoc syntax is based on
2238 <a href="http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html">
mark@chromium.org7b245632013-09-25 21:16:00 +00002239 JavaDoc</a>. Many tools extract metadata from JSDoc comments to
2240 perform code validation and optimizations. These comments must be
mark@chromium.orge33361f2011-11-04 16:55:22 +00002241 well-formed.</p>
2242
2243 <CODE_SNIPPET>
2244 /**
2245 * A JSDoc comment should begin with a slash and 2 asterisks.
2246 * Inline tags should be enclosed in braces like {@code this}.
2247 * @desc Block tags should always start on their own line.
2248 */
2249 </CODE_SNIPPET>
2250 </SUBSECTION>
2251
2252 <SUBSECTION title="JSDoc Indentation">
2253 <p>If you have to line break a block tag, you should treat this as
2254 breaking a code statement and indent it four spaces.</p>
2255
2256 <CODE_SNIPPET>
2257 /**
2258 * Illustrates line wrapping for long param/return descriptions.
2259 * @param {string} foo This is a param with a description too long to fit in
2260 * one line.
2261 * @return {number} This returns something that has a description too long to
2262 * fit in one line.
2263 */
2264 project.MyClass.prototype.method = function(foo) {
2265 return 5;
2266 };
2267 </CODE_SNIPPET>
2268
mark@chromium.org7b245632013-09-25 21:16:00 +00002269 <p>You should not indent the <code>@fileoverview</code> command. You do not have to
2270 indent the <code>@desc</code> command.</p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002271
2272 <p>Even though it is not preferred, it is also acceptable to line up
2273 the description.</p>
2274
2275 <CODE_SNIPPET>
2276 /**
2277 * This is NOT the preferred indentation method.
2278 * @param {string} foo This is a param with a description too long to fit in
2279 * one line.
2280 * @return {number} This returns something that has a description too long to
2281 * fit in one line.
2282 */
2283 project.MyClass.prototype.method = function(foo) {
2284 return 5;
2285 };
2286 </CODE_SNIPPET>
2287 </SUBSECTION>
2288
2289 <SUBSECTION title="HTML in JSDoc">
2290 <p>Like JavaDoc, JSDoc supports many HTML tags, like &lt;code&gt;,
2291 &lt;pre&gt;, &lt;tt&gt;, &lt;strong&gt;, &lt;ul&gt;, &lt;ol&gt;,
2292 &lt;li&gt;, &lt;a&gt;, and others.</p>
2293
2294 <p>This means that plaintext formatting is not respected. So, don't
2295 rely on whitespace to format JSDoc:</p>
2296
2297 <BAD_CODE_SNIPPET>
2298 /**
2299 * Computes weight based on three factors:
2300 * items sent
2301 * items received
2302 * last timestamp
2303 */
2304 </BAD_CODE_SNIPPET>
2305
2306 <p>It'll come out like this:</p>
2307
2308 <BAD_CODE_SNIPPET>
mark@chromium.org5684bbc2013-07-12 18:53:13 +00002309 Computes weight based on three factors: items sent items received last timestamp
mark@chromium.orge33361f2011-11-04 16:55:22 +00002310 </BAD_CODE_SNIPPET>
2311
2312 <p>Instead, do this:</p>
2313
2314 <CODE_SNIPPET>
2315 /**
2316 * Computes weight based on three factors:
2317 * &lt;ul&gt;
2318 * &lt;li&gt;items sent
2319 * &lt;li&gt;items received
2320 * &lt;li&gt;last timestamp
2321 * &lt;/ul&gt;
2322 */
2323 </CODE_SNIPPET>
2324
2325 The <a href="http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html">
2326 JavaDoc</a> style guide is a useful resource on how to write
2327 well-formed doc comments.
2328 </SUBSECTION>
robbyw@google.combb324012010-07-12 22:02:20 +00002329
2330 <SUBSECTION title="Top/File-Level Comments">
2331 <p>
2332
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002333 A <a href="copyright.html">copyright notice</a> and author information are optional.
mark@chromium.org5684bbc2013-07-12 18:53:13 +00002334 File overviews are generally recommended whenever a file consists of
2335 more than a single class definition. The top level comment is
2336 designed to orient readers unfamiliar with the code to what is in
2337 this file. If present, it should provide a description of the
2338 file's contents and any dependencies or compatibility information.
2339 As an example:
2340 </p>
robbyw@google.combb324012010-07-12 22:02:20 +00002341
2342 <CODE_SNIPPET>
robbyw@google.combb324012010-07-12 22:02:20 +00002343 /**
2344 * @fileoverview Description of file, its uses and information
2345 * about its dependencies.
robbyw@google.combb324012010-07-12 22:02:20 +00002346 */
2347 </CODE_SNIPPET>
2348
2349
2350 </SUBSECTION>
2351
2352 <SUBSECTION title="Class Comments">
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002353 <p>Classes must be documented with a description and a
2354 <a href="#constructor-tag">type tag that
2355 identifies the constructor</a>.
robbyw@google.combb324012010-07-12 22:02:20 +00002356 </p>
2357
2358 <CODE_SNIPPET>
2359 /**
2360 * Class making something fun and easy.
2361 * @param {string} arg1 An argument that makes this more interesting.
2362 * @param {Array.&lt;number&gt;} arg2 List of numbers to be processed.
2363 * @constructor
2364 * @extends {goog.Disposable}
2365 */
2366 project.MyClass = function(arg1, arg2) {
2367 // ...
2368 };
2369 goog.inherits(project.MyClass, goog.Disposable);
2370 </CODE_SNIPPET>
2371 </SUBSECTION>
2372
2373 <SUBSECTION title="Method and Function Comments">
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002374 <p>Parameter and return types should be documented. The method
2375 description may be omitted if it is obvious from the parameter
2376 or return type descriptions. Method descriptions should start
2377 with a sentence written in the third person declarative voice.</p>
robbyw@google.combb324012010-07-12 22:02:20 +00002378 <CODE_SNIPPET>
2379 /**
robbyw@google.combb324012010-07-12 22:02:20 +00002380 * Operates on an instance of MyClass and returns something.
2381 * @param {project.MyClass} obj Instance of MyClass which leads to a long
2382 * comment that needs to be wrapped to two lines.
mark@chromium.org5684bbc2013-07-12 18:53:13 +00002383 * @return {boolean} Whether something occurred.
robbyw@google.combb324012010-07-12 22:02:20 +00002384 */
2385 function PR_someMethod(obj) {
2386 // ...
2387 }
2388 </CODE_SNIPPET>
robbyw@google.combb324012010-07-12 22:02:20 +00002389 </SUBSECTION>
2390
2391 <SUBSECTION title="Property Comments">
robbyw@google.combb324012010-07-12 22:02:20 +00002392 <CODE_SNIPPET>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002393 /** @constructor */
2394 project.MyClass = function() {
2395 /**
2396 * Maximum number of things per pane.
2397 * @type {number}
2398 */
2399 this.someProperty = 4;
2400 }
robbyw@google.combb324012010-07-12 22:02:20 +00002401 </CODE_SNIPPET>
2402 </SUBSECTION>
2403
robbyw@google.combb324012010-07-12 22:02:20 +00002404 <SUBSECTION title="JSDoc Tag Reference">
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002405 <a name="JSDoc_Tag_Reference"/>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002406 <p/>
robbyw@google.combb324012010-07-12 22:02:20 +00002407 <table border="1" style="border-collapse:collapse" cellpadding="4">
2408 <thead>
2409 <tr>
2410 <th>Tag</th>
2411 <th>Template &amp; Examples</th>
2412 <th>Description</th>
robbyw@google.combb324012010-07-12 22:02:20 +00002413 </tr>
2414 </thead>
2415 <tbody>
2416 <tr>
robbyw@google.combb324012010-07-12 22:02:20 +00002417 <td>
2418 <a name="tag-author">@author</a>
2419
2420 </td>
2421 <td>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002422 <code>@author username@google.com (first last)</code>
robbyw@google.combb324012010-07-12 22:02:20 +00002423 <p><i>For example:</i></p>
2424 <CODE_SNIPPET>
2425 /**
2426 * @fileoverview Utilities for handling textareas.
2427 * @author kuth@google.com (Uthur Pendragon)
2428 */
2429 </CODE_SNIPPET>
2430 </td>
2431 <td>
2432 Document the author of a file or the owner of a test,
2433 generally only used in the <code>@fileoverview</code> comment.
2434
2435 </td>
robbyw@google.combb324012010-07-12 22:02:20 +00002436 </tr>
2437
mark@chromium.orge33361f2011-11-04 16:55:22 +00002438
robbyw@google.combb324012010-07-12 22:02:20 +00002439
2440 <tr>
2441 <td><a name="tag-code">@code</a></td>
2442 <td>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002443 <code>{@code ...}</code>
robbyw@google.combb324012010-07-12 22:02:20 +00002444 <p><i>For example:</i></p>
2445 <CODE_SNIPPET>
2446 /**
2447 * Moves to the next position in the selection.
2448 * Throws {@code goog.iter.StopIteration} when it
2449 * passes the end of the range.
2450 * @return {Node} The node at the next position.
2451 */
2452 goog.dom.RangeIterator.prototype.next = function() {
2453 // ...
2454 };
2455 </CODE_SNIPPET>
2456 </td>
2457 <td>
2458 Indicates that a term in a JSDoc description is code so it may
2459 be correctly formatted in generated documentation.
2460 </td>
robbyw@google.combb324012010-07-12 22:02:20 +00002461 </tr>
2462
2463 <tr>
2464 <td><a name="tag-const">@const</a></td>
2465 <td>
mark@chromium.org8190c132013-03-21 16:03:26 +00002466 <code>@const</code><br/>
2467 <code>@const {type}</code>
robbyw@google.combb324012010-07-12 22:02:20 +00002468 <p><i>For example:</i></p>
2469 <CODE_SNIPPET>
2470 /** @const */ var MY_BEER = 'stout';
2471
2472 /**
2473 * My namespace's favorite kind of beer.
mark@chromium.org8190c132013-03-21 16:03:26 +00002474 * @const {string}
robbyw@google.combb324012010-07-12 22:02:20 +00002475 */
2476 mynamespace.MY_BEER = 'stout';
2477
2478 /** @const */ MyClass.MY_BEER = 'stout';
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002479
2480 /**
2481 * Initializes the request.
2482 * @const
2483 */
2484 mynamespace.Request.prototype.initialize = function() {
mark@chromium.org5684bbc2013-07-12 18:53:13 +00002485 // This method cannot be overridden in a subclass.
mark@chromium.org7b245632013-09-25 21:16:00 +00002486 };
robbyw@google.combb324012010-07-12 22:02:20 +00002487 </CODE_SNIPPET>
2488 </td>
2489 <td>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002490 <p>Marks a variable (or property) as read-only and suitable
2491 for inlining.</p>
2492
mark@chromium.org7b245632013-09-25 21:16:00 +00002493 <p>A <code>@const</code> variable is an immutable pointer to
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002494 a value. If a variable or property marked as
2495 <code>@const</code> is overwritten, JSCompiler will give
2496 warnings.</p>
2497
2498 <p>The type declaration of a constant value can be omitted
2499 if it can be clearly inferred. An additional comment about
2500 the variable is optional.</p>
2501
2502 <p>When <code>@const</code> is applied to a method, it
2503 implies the method is not only not overwritable, but also
mark@chromium.org8190c132013-03-21 16:03:26 +00002504 that the method is <em>finalized</em>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002505 not overridable in subclasses.</p>
2506
2507 <p>For more on <code>@const</code>, see the
2508 <a href="#Constants">Constants</a> section.</p>
2509
robbyw@google.combb324012010-07-12 22:02:20 +00002510 </td>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002511 </tr>
2512
2513 <tr>
2514 <td><a name="tag-constructor">@constructor</a></td>
2515 <td>
2516 <code>@constructor</code>
2517 <p><i>For example:</i></p>
2518 <CODE_SNIPPET>
2519 /**
2520 * A rectangle.
2521 * @constructor
2522 */
2523 function GM_Rect() {
2524 ...
2525 }
2526 </CODE_SNIPPET>
2527 </td>
2528 <td>
2529 Used in a class's documentation to indicate the constructor.
2530 </td>
2531 </tr>
2532
2533 <tr>
2534 <td><a name="tag-define">@define</a></td>
2535 <td>
2536 <code>@define {Type} description</code>
2537 <p><i>For example:</i></p>
2538 <CODE_SNIPPET>
2539 /** @define {boolean} */
2540 var TR_FLAGS_ENABLE_DEBUG = true;
2541
mark@chromium.org7b245632013-09-25 21:16:00 +00002542 /**
2543 * @define {boolean} Whether we know at compile-time that
2544 * the browser is IE.
2545 */
mark@chromium.orge33361f2011-11-04 16:55:22 +00002546 goog.userAgent.ASSUME_IE = false;
2547 </CODE_SNIPPET>
2548 </td>
2549 <td>
2550 Indicates a constant that can be overridden by the compiler at
2551 compile-time. In the example, the compiler flag
2552 <code>--define='goog.userAgent.ASSUME_IE=true'</code>
2553 could be specified in the BUILD file to indicate that the
2554 constant <code>goog.userAgent.ASSUME_IE</code> should be replaced
2555 with <code>true</code>.
2556 </td>
2557 </tr>
2558
2559 <tr>
2560 <td><a name="tag-deprecated">@deprecated</a></td>
2561 <td>
2562 <code>@deprecated Description</code>
2563 <p><i>For example:</i></p>
2564 <CODE_SNIPPET>
2565 /**
2566 * Determines whether a node is a field.
2567 * @return {boolean} True if the contents of
2568 * the element are editable, but the element
2569 * itself is not.
2570 * @deprecated Use isField().
2571 */
2572 BN_EditUtil.isTopEditableField = function(node) {
2573 // ...
2574 };
2575 </CODE_SNIPPET>
2576 </td>
2577 <td>
2578 Used to tell that a function, method or property should not be
2579 used any more. Always provide instructions on what callers
2580 should use instead.
2581 </td>
2582 </tr>
2583
2584 <tr>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002585 <td><a name="tag-dict">@dict</a></td>
2586 <td>
2587 <code>@dict Description</code>
2588 <p><i>For example:</i></p>
2589 <CODE_SNIPPET>
2590 /**
2591 * @constructor
2592 * @dict
2593 */
2594 function Foo(x) {
2595 this['x'] = x;
2596 }
2597 var obj = new Foo(123);
2598 var num = obj.x; // warning
2599
2600 (/** @dict */ { x: 1 }).x = 123; // warning
2601 </CODE_SNIPPET>
2602 </td>
2603 <td>
2604 When a constructor (<code>Foo</code> in the example) is
2605 annotated with <code>@dict</code>, you can only use the
2606 bracket notation to access the properties of <code>Foo</code>
2607 objects.
2608 The annotation can also be used directly on object literals.
2609 </td>
2610 </tr>
2611
2612 <tr>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002613 <td><a name="tag-enum">@enum</a></td>
2614 <td>
2615 <code>@enum {Type}</code>
2616 <p><i>For example:</i></p>
2617 <CODE_SNIPPET>
2618 /**
2619 * Enum for tri-state values.
2620 * @enum {number}
2621 */
2622 project.TriState = {
2623 TRUE: 1,
2624 FALSE: -1,
2625 MAYBE: 0
2626 };
2627 </CODE_SNIPPET>
2628 </td>
2629 </tr>
2630
2631 <tr>
2632 <td><a name="tag-export">@export</a></td>
2633 <td>
2634 <code>@export</code>
2635 <p><i>For example:</i></p>
2636 <CODE_SNIPPET>
2637 /** @export */
2638 foo.MyPublicClass.prototype.myPublicMethod = function() {
2639 // ...
2640 };
2641 </CODE_SNIPPET>
2642 </td>
2643 <td>
2644 <p>Given the code on the left, when the compiler is run with
2645 the <code>--generate_exports</code> flag, it will generate the
2646 code:</p>
2647 <CODE_SNIPPET>
2648 goog.exportSymbol('foo.MyPublicClass.prototype.myPublicMethod',
2649 foo.MyPublicClass.prototype.myPublicMethod);
2650 </CODE_SNIPPET>
2651 <p>which will export the symbols to uncompiled code.
2652 Code that uses the <code>@export</code> annotation must either</p>
2653 <ol>
2654 <li>include <code>//javascript/closure/base.js</code>, or</li>
2655 <li>define both <code>goog.exportSymbol</code> and
2656 <code>goog.exportProperty</code> with the same method
2657 signature in their own codebase.</li>
2658 </ol>
2659 </td>
2660 </tr>
2661
2662 <tr>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002663 <td><a name="tag-expose">@expose</a></td>
2664 <td>
2665 <code>@expose</code>
2666 <p><i>For example:</i></p>
2667 <CODE_SNIPPET>
2668 /** @expose */
2669 MyClass.prototype.exposedProperty = 3;
2670 </CODE_SNIPPET>
2671 </td>
2672 <td>
2673 <p>
2674 Declares an exposed property. Exposed properties
2675 will not be removed, or renamed, or collapsed,
2676 or optimized in any way by the compiler. No properties
2677 with the same name will be able to be optimized either.
2678 </p>
2679
2680 <p>
2681 <code>@expose</code> should never be used in library code,
2682 because it will prevent that property from ever getting
2683 removed.
2684 </p>
2685 </td>
2686 </tr>
2687
2688 <tr>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002689 <td><a name="tag-extends">@extends</a></td>
2690 <td>
2691 <code>
2692 @extends Type<br/>
2693 @extends {Type}
2694 </code>
2695 <p><i>For example:</i></p>
2696 <CODE_SNIPPET>
2697 /**
2698 * Immutable empty node list.
2699 * @constructor
2700 * @extends goog.ds.BasicNodeList
2701 */
2702 goog.ds.EmptyNodeList = function() {
2703 ...
2704 };
2705 </CODE_SNIPPET>
2706 </td>
2707 <td>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002708 Used with <code>@constructor</code> to indicate that a class
2709 inherits from another class. Curly braces around the type are
2710 optional.
mark@chromium.orge33361f2011-11-04 16:55:22 +00002711 </td>
2712 </tr>
2713
2714 <tr>
2715 <td><a name="tag-externs">@externs</a></td>
2716 <td>
2717 <code>@externs</code>
2718 <p><i>For example:</i></p>
2719 <CODE_SNIPPET>
2720 /**
2721 * @fileoverview This is an externs file.
2722 * @externs
2723 */
2724
2725 var document;
2726 </CODE_SNIPPET>
2727 </td>
2728 <td>
2729 <p>
2730 Declares an
2731
2732 externs file.
2733 </p>
2734
2735
2736 </td>
2737 </tr>
2738
2739 <tr>
2740 <td><a name="tag-fileoverview">@fileoverview</a></td>
2741 <td>
2742 <code>@fileoverview Description</code>
2743 <p><i>For example:</i></p>
2744 <CODE_SNIPPET>
2745 /**
2746 * @fileoverview Utilities for doing things that require this very long
2747 * but not indented comment.
2748 * @author kuth@google.com (Uthur Pendragon)
2749 */
2750 </CODE_SNIPPET>
2751 </td>
2752 <td>Makes the comment block provide file level information.</td>
2753 </tr>
2754
2755 <tr>
2756 <td><a name="tag-implements">@implements</a></td>
2757 <td>
2758 <code>
2759 @implements Type<br/>
2760 @implements {Type}
2761 </code>
2762 <p><i>For example:</i></p>
2763 <CODE_SNIPPET>
2764 /**
2765 * A shape.
2766 * @interface
2767 */
2768 function Shape() {};
2769 Shape.prototype.draw = function() {};
2770
2771 /**
2772 * @constructor
2773 * @implements {Shape}
2774 */
2775 function Square() {};
2776 Square.prototype.draw = function() {
2777 ...
2778 };
2779 </CODE_SNIPPET>
2780 </td>
2781 <td>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002782 Used with <code>@constructor</code> to indicate that a class
2783 implements an interface. Curly braces around the type are
2784 optional.
mark@chromium.orge33361f2011-11-04 16:55:22 +00002785 </td>
2786 </tr>
2787
2788 <tr>
2789 <td><a name="tag-inheritDoc">@inheritDoc</a></td>
2790 <td>
2791 <code>@inheritDoc</code>
2792 <p><i>For example:</i></p>
2793 <CODE_SNIPPET>
2794 /** @inheritDoc */
2795 project.SubClass.prototype.toString() {
2796 // ...
2797 };
2798 </CODE_SNIPPET>
2799 </td>
2800 <td>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002801 <p style="font-weight:bold">Deprecated. Use
2802 <code>@override</code> instead.</p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002803
2804 Indicates that a method or property of a subclass
2805 intentionally hides a method or property of the superclass,
2806 and has exactly the same documentation. Notice that
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002807 <code>@inheritDoc</code> implies <code>@override</code>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002808 </td>
2809 </tr>
2810
2811 <tr>
2812 <td><a name="tag-interface">@interface</a></td>
2813 <td>
2814 <code>@interface</code>
2815 <p><i>For example:</i></p>
2816 <CODE_SNIPPET>
2817 /**
2818 * A shape.
2819 * @interface
2820 */
2821 function Shape() {};
2822 Shape.prototype.draw = function() {};
2823
2824 /**
2825 * A polygon.
2826 * @interface
2827 * @extends {Shape}
2828 */
2829 function Polygon() {};
2830 Polygon.prototype.getSides = function() {};
2831 </CODE_SNIPPET>
2832 </td>
mark@chromium.org5684bbc2013-07-12 18:53:13 +00002833 <td>
2834 Used to indicate that the function defines an interface.
2835 </td>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002836 </tr>
2837
2838 <tr>
2839 <td><a name="tag-lends">@lends</a></td>
2840 <td>
2841 <code>@lends objectName</code><br/>
2842 <code>@lends {objectName}</code>
2843 <p><i>For example:</i></p>
2844 <CODE_SNIPPET>
2845 goog.object.extend(
2846 Button.prototype,
2847 /** @lends {Button.prototype} */ {
2848 isButton: function() { return true; }
2849 });
2850 </CODE_SNIPPET>
2851 </td>
2852 <td>
2853 Indicates that the keys of an object literal should
2854 be treated as properties of some other object. This annotation
2855 should only appear on object literals.<p/>
2856
2857 Notice that the name in braces is not a type name like
2858 in other annotations. It's an object name. It names
2859 the object on which the properties are "lent".
2860 For example, <code>@type {Foo}</code> means "an instance of Foo",
2861 but <code>@lends {Foo}</code> means "the constructor Foo".<p/>
2862
2863 The <a href="http://code.google.com/p/jsdoc-toolkit/wiki/TagLends">
2864 JSDoc Toolkit docs</a> have more information on this
2865 annotation.
2866 </td>
2867 </tr>
2868
2869 <tr>
2870 <td><a name="tag-license">@license</a> or
2871 <a name="tag-preserve">@preserve</a></td>
2872 <td>
2873 <code>@license Description</code>
2874 <p><i>For example:</i></p>
2875 <CODE_SNIPPET>
2876 /**
2877 * @preserve Copyright 2009 SomeThirdParty.
2878 * Here is the full license text and copyright
2879 * notice for this file. Note that the notice can span several
2880 * lines and is only terminated by the closing star and slash:
2881 */
2882 </CODE_SNIPPET>
2883 </td>
2884 <td>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002885 Anything marked by <code>@license</code> or
2886 <code>@preserve</code> will be retained by the compiler and
2887 output at the top of the compiled code for that file. This
2888 annotation allows important notices (such as legal licenses or
2889 copyright text) to survive compilation unchanged. Line breaks
2890 are preserved.
mark@chromium.orge33361f2011-11-04 16:55:22 +00002891 </td>
2892 </tr>
2893
mark@chromium.org8190c132013-03-21 16:03:26 +00002894
2895
2896
2897
mark@chromium.orge33361f2011-11-04 16:55:22 +00002898 <tr>
2899 <td><a name="tag-noalias">@noalias</a></td>
2900 <td>
2901 <code>@noalias</code>
2902 <p><i>For example:</i></p>
2903 <CODE_SNIPPET>
2904 /** @noalias */
2905 function Range() {}
2906 </CODE_SNIPPET>
2907 </td>
2908 <td>
2909 Used in an externs file to indicate to the compiler that the
2910 variable or function should not be aliased as part of the
2911 alias externals pass of the compiler.
2912 </td>
robbyw@google.combb324012010-07-12 22:02:20 +00002913 </tr>
2914
2915 <tr>
mark@chromium.org7b245632013-09-25 21:16:00 +00002916 <td><a name="tag-nocompile">@nocompile</a></td>
2917 <td>
2918 <code>@nocompile</code>
2919 <p><i>For example:</i></p>
2920 <CODE_SNIPPET>
2921 /** @nocompile */
2922
2923 // JavaScript code
2924 </CODE_SNIPPET>
2925 </td>
2926 <td>
2927 Used at the top of a file to tell the compiler to parse this
2928 file but not compile it.
2929 Code that is not meant for compilation and should be omitted
2930 from compilation tests (such as bootstrap code) uses this
2931 annotation.
2932 Use sparingly.
2933 </td>
2934 </tr>
2935
2936 <tr>
robbyw@google.combb324012010-07-12 22:02:20 +00002937 <td><a name="tag-nosideeffects">@nosideeffects</a></td>
2938 <td>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002939 <code>@nosideeffects</code>
robbyw@google.combb324012010-07-12 22:02:20 +00002940 <p><i>For example:</i></p>
2941 <CODE_SNIPPET>
2942 /** @nosideeffects */
2943 function noSideEffectsFn1() {
2944 // ...
mark@chromium.org7b245632013-09-25 21:16:00 +00002945 }
robbyw@google.combb324012010-07-12 22:02:20 +00002946
2947 /** @nosideeffects */
2948 var noSideEffectsFn2 = function() {
2949 // ...
2950 };
2951
2952 /** @nosideeffects */
2953 a.prototype.noSideEffectsFn3 = function() {
2954 // ...
2955 };
2956 </CODE_SNIPPET>
2957 </td>
2958 <td>
2959 This annotation can be used as part of function and
2960 constructor declarations to indicate that calls to the
2961 declared function have no side-effects. This annotation
2962 allows the compiler to remove calls to these functions if the
2963 return value is not used.
2964 </td>
robbyw@google.combb324012010-07-12 22:02:20 +00002965 </tr>
2966
2967 <tr>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002968 <td><a name="tag-override">@override</a></td>
robbyw@google.combb324012010-07-12 22:02:20 +00002969 <td>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002970 <code>@override</code>
robbyw@google.combb324012010-07-12 22:02:20 +00002971 <p><i>For example:</i></p>
2972 <CODE_SNIPPET>
mark@chromium.orge33361f2011-11-04 16:55:22 +00002973 /**
2974 * @return {string} Human-readable representation of project.SubClass.
2975 * @override
2976 */
mark@chromium.org7b245632013-09-25 21:16:00 +00002977 project.SubClass.prototype.toString = function() {
mark@chromium.orge33361f2011-11-04 16:55:22 +00002978 // ...
2979 };
2980 </CODE_SNIPPET>
2981 </td>
2982 <td>
2983 Indicates that a method or property of a subclass
2984 intentionally hides a method or property of the superclass. If
2985 no other documentation is included, the method or property
2986 also inherits documentation from its superclass.
2987 </td>
2988 </tr>
robbyw@google.combb324012010-07-12 22:02:20 +00002989
mark@chromium.orge33361f2011-11-04 16:55:22 +00002990 <tr>
2991 <td><a name="tag-param">@param</a></td>
2992 <td>
2993 <code>@param {Type} varname Description</code>
2994 <p><i>For example:</i></p>
2995 <CODE_SNIPPET>
2996 /**
2997 * Queries a Baz for items.
2998 * @param {number} groupNum Subgroup id to query.
2999 * @param {string|number|null} term An itemName,
3000 * or itemId, or null to search everything.
3001 */
3002 goog.Baz.prototype.query = function(groupNum, term) {
3003 // ...
3004 };
3005 </CODE_SNIPPET>
3006 </td>
3007 <td>
3008 Used with method, function and constructor calls to document
3009 the arguments of a function.<p/>
3010
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00003011 <a href="#JsTypes">Type</a>
3012 names must be enclosed in curly braces. If the type
mark@chromium.orge33361f2011-11-04 16:55:22 +00003013 is omitted, the compiler will not type-check the parameter.
3014 </td>
3015 </tr>
3016
3017 <tr>
3018 <td><a name="tag-private">@private</a></td>
3019 <td>
mark@chromium.org8190c132013-03-21 16:03:26 +00003020 <code>@private</code><br/>
3021 <code>@private {type}</code>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003022 <p><i>For example:</i></p>
3023 <CODE_SNIPPET>
3024 /**
3025 * Handlers that are listening to this logger.
mark@chromium.org8190c132013-03-21 16:03:26 +00003026 * @private {!Array.&lt;Function&gt;}
mark@chromium.orge33361f2011-11-04 16:55:22 +00003027 */
3028 this.handlers_ = [];
3029 </CODE_SNIPPET>
3030 </td>
3031 <td>
3032 Used in conjunction with a trailing underscore on the method
3033 or property name to indicate that the member is
mark@chromium.org7b245632013-09-25 21:16:00 +00003034 <a href="#Visibility__private_and_protected_fields_">private</a> and final.
mark@chromium.orge33361f2011-11-04 16:55:22 +00003035 </td>
3036 </tr>
3037
3038 <tr>
3039 <td><a name="tag-protected">@protected</a></td>
3040 <td>
mark@chromium.org8190c132013-03-21 16:03:26 +00003041 <code>@protected</code><br/>
3042 <code>@protected {type}</code>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003043 <p><i>For example:</i></p>
3044 <CODE_SNIPPET>
3045 /**
mark@chromium.org7b245632013-09-25 21:16:00 +00003046 * Sets the component's root element to the given element.
mark@chromium.orge33361f2011-11-04 16:55:22 +00003047 * @param {Element} element Root element for the component.
3048 * @protected
3049 */
3050 goog.ui.Component.prototype.setElementInternal = function(element) {
3051 // ...
3052 };
3053 </CODE_SNIPPET>
3054 </td>
3055 <td>
3056 Used to indicate that the member or property is
3057 <a href="#Visibility__private_and_protected_fields_">protected</a>.
3058 Should be used in conjunction with names with no trailing
3059 underscore.
3060 </td>
3061 </tr>
3062
3063 <tr>
mark@chromium.org7b245632013-09-25 21:16:00 +00003064 <td><a name="tag-public">@public</a></td>
3065 <td>
3066 <code>@public</code><br/>
3067 <code>@public {type}</code>
3068 <p><i>For example:</i></p>
3069 <CODE_SNIPPET>
3070 /**
3071 * Whether to cancel the event in internal capture/bubble processing.
3072 * @public {boolean}
3073 * @suppress {visiblity} Referencing this outside this package is strongly
3074 * discouraged.
3075 */
3076 goog.events.Event.prototype.propagationStopped_ = false;
3077 </CODE_SNIPPET>
3078 </td>
3079 <td>
3080 Used to indicate that the member or property is public. Variables and
3081 properties are public by default, so this annotation is rarely necessary.
3082 Should only be used in legacy code that cannot be easily changed to
3083 override the visibility of members that were named as private variables.
3084 </td>
3085 </tr>
3086
3087 <tr>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003088 <td><a name="tag-return">@return</a></td>
3089 <td>
3090 <code>@return {Type} Description</code>
3091 <p><i>For example:</i></p>
3092 <CODE_SNIPPET>
3093 /**
3094 * @return {string} The hex ID of the last item.
3095 */
3096 goog.Baz.prototype.getLastId = function() {
3097 // ...
3098 return id;
3099 };
3100 </CODE_SNIPPET>
3101 </td>
3102 <td>
3103 Used with method and function calls to document the return
3104 type. When writing descriptions for boolean parameters,
3105 prefer "Whether the component is visible" to "True if the
3106 component is visible, false otherwise". If there is no return
3107 value, do not use an <code>@return</code> tag.<p/>
3108
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00003109 <a href="#JsTypes">Type</a>
3110 names must be enclosed in curly braces. If the type
mark@chromium.orge33361f2011-11-04 16:55:22 +00003111 is omitted, the compiler will not type-check the return value.
3112 </td>
3113 </tr>
3114
3115 <tr>
3116 <td><a name="tag-see">@see</a></td>
3117 <td>
3118 <code>@see Link</code>
3119 <p><i>For example:</i></p>
3120 <CODE_SNIPPET>
3121 /**
3122 * Adds a single item, recklessly.
3123 * @see #addSafely
3124 * @see goog.Collect
3125 * @see goog.RecklessAdder#add
3126 ...
3127 </CODE_SNIPPET>
3128 </td>
3129 <td>Reference a lookup to another class function or method.</td>
3130 </tr>
3131
3132 <tr>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00003133 <td><a name="tag-struct">@struct</a></td>
3134 <td>
3135 <code>@struct Description</code>
3136 <p><i>For example:</i></p>
3137 <CODE_SNIPPET>
3138 /**
3139 * @constructor
3140 * @struct
3141 */
3142 function Foo(x) {
3143 this.x = x;
3144 }
3145 var obj = new Foo(123);
3146 var num = obj['x']; // warning
3147 obj.y = "asdf"; // warning
3148
3149 Foo.prototype = /** @struct */ {
3150 method1: function() {}
3151 };
3152 Foo.prototype.method2 = function() {}; // warning
3153 </CODE_SNIPPET>
3154 </td>
3155 <td>
3156 When a constructor (<code>Foo</code> in the example) is
3157 annotated with <code>@struct</code>, you can only use the dot
3158 notation to access the properties of <code>Foo</code> objects.
3159 Also, you cannot add new properties to <code>Foo</code>
3160 objects after they have been created.
3161 The annotation can also be used directly on object literals.
3162 </td>
3163 </tr>
3164
3165 <tr>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003166 <td><a name="tag-supported">@supported</a></td>
3167 <td>
3168 <code>@supported Description</code>
3169 <p><i>For example:</i></p>
3170 <CODE_SNIPPET>
3171 /**
3172 * @fileoverview Event Manager
3173 * Provides an abstracted interface to the
3174 * browsers' event systems.
3175 * @supported So far tested in IE6 and FF1.5
3176 */
3177 </CODE_SNIPPET>
3178 </td>
3179 <td>
3180 Used in a fileoverview to indicate what browsers are supported
3181 by the file.
3182 </td>
3183 </tr>
3184
3185 <tr>
3186 <td><a name="tag-suppress">@suppress</a></td>
3187 <td>
3188 <code>
3189 @suppress {warning1|warning2}
3190 </code>
mark@chromium.org7b245632013-09-25 21:16:00 +00003191 <code>
3192 @suppress {warning1,warning2}
3193 </code>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003194 <p><i>For example:</i></p>
3195 <CODE_SNIPPET>
3196 /**
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00003197 * @suppress {deprecated}
mark@chromium.orge33361f2011-11-04 16:55:22 +00003198 */
3199 function f() {
3200 deprecatedVersionOfF();
robbyw@google.combb324012010-07-12 22:02:20 +00003201 }
3202 </CODE_SNIPPET>
3203 </td>
3204 <td>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003205 Suppresses warnings from tools. Warning categories are
mark@chromium.org7b245632013-09-25 21:16:00 +00003206 separated by <code>|</code> or <code>,</code>.
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00003207
robbyw@google.combb324012010-07-12 22:02:20 +00003208 </td>
robbyw@google.combb324012010-07-12 22:02:20 +00003209 </tr>
3210
mmentovaicd4ce0f2011-03-29 20:30:47 +00003211 <tr>
3212 <td><a name="tag-template">@template</a></td>
3213 <td>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003214 <code>@template</code>
mmentovaicd4ce0f2011-03-29 20:30:47 +00003215 <p><i>For example:</i></p>
3216 <CODE_SNIPPET>
3217 /**
3218 * @param {function(this:T, ...)} fn
3219 * @param {T} thisObj
3220 * @param {...*} var_args
3221 * @template T
3222 */
3223 goog.bind = function(fn, thisObj, var_args) {
mark@chromium.org7b245632013-09-25 21:16:00 +00003224 ...
mmentovaicd4ce0f2011-03-29 20:30:47 +00003225 };
3226 </CODE_SNIPPET>
3227 </td>
3228 <td>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003229 This annotation can be used to declare a
3230 <a href="#Template_types">template typename</a>.
mmentovaicd4ce0f2011-03-29 20:30:47 +00003231 </td>
mmentovaicd4ce0f2011-03-29 20:30:47 +00003232 </tr>
mmentovai7f003d32010-11-23 21:09:55 +00003233
robbyw@google.combb324012010-07-12 22:02:20 +00003234 <tr>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003235 <td><a name="tag-this">@this</a></td>
robbyw@google.combb324012010-07-12 22:02:20 +00003236 <td>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003237 <code>
3238 @this Type<br/>
3239 @this {Type}
3240 </code>
robbyw@google.combb324012010-07-12 22:02:20 +00003241 <p><i>For example:</i></p>
3242 <CODE_SNIPPET>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003243 pinto.chat.RosterWidget.extern('getRosterElement',
robbyw@google.combb324012010-07-12 22:02:20 +00003244 /**
mark@chromium.orge33361f2011-11-04 16:55:22 +00003245 * Returns the roster widget element.
3246 * @this pinto.chat.RosterWidget
3247 * @return {Element}
robbyw@google.combb324012010-07-12 22:02:20 +00003248 */
mark@chromium.orge33361f2011-11-04 16:55:22 +00003249 function() {
3250 return this.getWrappedComponent_().getElement();
3251 });
robbyw@google.combb324012010-07-12 22:02:20 +00003252 </CODE_SNIPPET>
3253 </td>
3254 <td>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003255 The type of the object in whose context a particular method is
3256 called. Required when the <code>this</code> keyword is referenced
3257 from a function that is not a prototype method.
robbyw@google.combb324012010-07-12 22:02:20 +00003258 </td>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003259 </tr>
3260
3261 <tr>
3262 <td><a name="tag-type">@type</a></td>
3263 <td>
3264 <code>
3265 @type Type<br/>
3266 @type {Type}
3267 </code>
3268 <p><i>For example:</i></p>
3269 <CODE_SNIPPET>
3270 /**
3271 * The message hex ID.
3272 * @type {string}
3273 */
3274 var hexId = hexId;
3275 </CODE_SNIPPET>
3276 </td>
3277 <td>
mark@chromium.org5684bbc2013-07-12 18:53:13 +00003278 Identifies the <a href="#JsTypes">type</a> of a variable,
3279 property, or expression. Curly braces are not required around
3280 most types, but some projects mandate them for all types, for
3281 consistency.
mark@chromium.orge33361f2011-11-04 16:55:22 +00003282 </td>
3283 </tr>
3284
3285 <tr>
3286 <td><a name="tag-typedef">@typedef</a></td>
3287 <td>
3288 <code>@typedef</code>
3289 <p><i>For example:</i></p>
3290 <CODE_SNIPPET>
3291 /** @typedef {(string|number)} */
3292 goog.NumberLike;
3293
3294 /** @param {goog.NumberLike} x A number or a string. */
3295 goog.readNumber = function(x) {
3296 ...
3297 }
3298 </CODE_SNIPPET>
3299 </td>
3300 <td>
3301 This annotation can be used to declare an alias of a more
3302 <a href="#Typedefs">complex type</a>.
3303 </td>
robbyw@google.combb324012010-07-12 22:02:20 +00003304 </tr>
mark@chromium.org8190c132013-03-21 16:03:26 +00003305
3306
3307
robbyw@google.combb324012010-07-12 22:02:20 +00003308 </tbody>
3309 </table>
3310
mark@chromium.org5684bbc2013-07-12 18:53:13 +00003311
3312
robbyw@google.combb324012010-07-12 22:02:20 +00003313 <p>
3314 You may also see other types of JSDoc annotations in third-party
3315 code. These annotations appear in the
3316 <a href="http://code.google.com/p/jsdoc-toolkit/wiki/TagReference">
3317 JSDoc Toolkit Tag Reference
3318 </a>
3319 but are currently discouraged in Google code. You should consider
3320 them "reserved" names for future use. These include:
3321 <ul>
3322 <li>@augments</li>
3323 <li>@argument</li>
3324 <li>@borrows</li>
3325 <li>@class</li>
3326 <li>@constant</li>
3327 <li>@constructs</li>
3328 <li>@default</li>
3329 <li>@event</li>
3330 <li>@example</li>
3331 <li>@field</li>
3332 <li>@function</li>
3333 <li>@ignore</li>
3334 <li>@inner</li>
robbyw@google.combb324012010-07-12 22:02:20 +00003335 <li>@link</li>
3336 <li>@memberOf</li>
3337 <li>@name</li>
3338 <li>@namespace</li>
3339 <li>@property</li>
3340 <li>@public</li>
3341 <li>@requires</li>
3342 <li>@returns</li>
3343 <li>@since</li>
3344 <li>@static</li>
3345 <li>@version</li>
3346 </ul>
3347 </p>
3348 </SUBSECTION>
mark@chromium.orge33361f2011-11-04 16:55:22 +00003349 </BODY>
3350 </STYLEPOINT>
robbyw@google.combb324012010-07-12 22:02:20 +00003351
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00003352 <STYLEPOINT title="Providing Dependencies With goog.provide">
mark@chromium.orge33361f2011-11-04 16:55:22 +00003353 <SUMMARY>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00003354 Only provide top-level symbols.
mark@chromium.orge33361f2011-11-04 16:55:22 +00003355 </SUMMARY>
3356 <BODY>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00003357 <p>
3358 All members defined on a class should be in the same file. So, only
3359 top-level classes should be provided in a file that contains multiple
3360 members defined on the same class (e.g. enums, inner classes, etc).
3361 </p>
3362 <p>Do this:</p>
3363 <CODE_SNIPPET>
3364 goog.provide('namespace.MyClass');
3365 </CODE_SNIPPET>
3366 <p>Not this:</p>
3367 <BAD_CODE_SNIPPET>
3368 goog.provide('namespace.MyClass');
3369 goog.provide('namespace.MyClass.Enum');
3370 goog.provide('namespace.MyClass.InnerClass');
3371 goog.provide('namespace.MyClass.TypeDef');
3372 goog.provide('namespace.MyClass.CONSTANT');
3373 goog.provide('namespace.MyClass.staticMethod');
3374 </BAD_CODE_SNIPPET>
3375 <p>
3376 Members on namespaces may also be provided:
3377 </p>
3378 <CODE_SNIPPET>
3379 goog.provide('foo.bar');
3380 goog.provide('foo.bar.method');
3381 goog.provide('foo.bar.CONSTANT');
3382 </CODE_SNIPPET>
robbyw@google.combb324012010-07-12 22:02:20 +00003383 </BODY>
3384 </STYLEPOINT>
3385
3386 <STYLEPOINT title="Compiling">
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00003387 <SUMMARY>Required</SUMMARY>
robbyw@google.combb324012010-07-12 22:02:20 +00003388 <BODY>
3389
3390
3391 <p>Use of JS compilers such as the
3392 <a href="http://code.google.com/closure/compiler/">Closure Compiler</a>
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00003393 is required for all customer-facing code.</p>
robbyw@google.combb324012010-07-12 22:02:20 +00003394
3395
3396
3397
3398 </BODY>
3399 </STYLEPOINT>
3400
3401 <STYLEPOINT title="Tips and Tricks">
3402 <SUMMARY>JavaScript tidbits</SUMMARY>
3403 <BODY>
3404 <SUBSECTION title="True and False Boolean Expressions">
3405 <p>The following are all false in boolean expressions:</p>
3406 <ul>
3407 <li><code>null</code></li>
3408 <li><code>undefined</code></li>
3409 <li><code>''</code> the empty string</li>
3410 <li><code>0</code> the number</li>
3411 </ul>
3412 <p>But be careful, because these are all true:</p>
3413 <ul>
3414 <li><code>'0'</code> the string</li>
3415 <li><code>[]</code> the empty array</li>
3416 <li><code>{}</code> the empty object</li>
3417 </ul>
3418
3419 <p>This means that instead of this:</p>
3420 <BAD_CODE_SNIPPET>
3421 while (x != null) {
3422 </BAD_CODE_SNIPPET>
3423 <p>you can write this shorter code (as long as you don't expect x to
3424 be 0, or the empty string, or false):</p>
3425 <CODE_SNIPPET>
3426 while (x) {
3427 </CODE_SNIPPET>
3428
3429 <p>And if you want to check a string to see if it is null or empty,
3430 you could do this:</p>
3431 <BAD_CODE_SNIPPET>
3432 if (y != null &amp;&amp; y != '') {
3433 </BAD_CODE_SNIPPET>
3434 <p>But this is shorter and nicer:</p>
3435 <CODE_SNIPPET>
3436 if (y) {
3437 </CODE_SNIPPET>
3438
3439 <p><strong>Caution:</strong> There are many unintuitive things about
3440 boolean expressions. Here are some of them:</p>
3441 <ul>
3442 <li><code>
3443 Boolean('0') == true<br/>
3444 '0' != true</code></li>
3445 <li><code>
3446 0 != null<br/>
3447 0 == []<br/>
3448 0 == false</code></li>
3449 <li><code>
3450 Boolean(null) == false<br/>
3451 null != true<br/>
3452 null != false</code></li>
3453 <li><code>
3454 Boolean(undefined) == false<br/>
3455 undefined != true<br/>
3456 undefined != false</code></li>
3457 <li><code>
3458 Boolean([]) == true<br/>
3459 [] != true<br/>
3460 [] == false</code></li>
3461 <li><code>
3462 Boolean({}) == true<br/>
3463 {} != true<br/>
3464 {} != false</code></li>
3465 </ul>
3466 </SUBSECTION>
3467
3468 <SUBSECTION title="Conditional (Ternary) Operator (?:)">
3469 <p>Instead of this:</p>
3470 <CODE_SNIPPET>
mark@chromium.org7b245632013-09-25 21:16:00 +00003471 if (val) {
robbyw@google.combb324012010-07-12 22:02:20 +00003472 return foo();
3473 } else {
3474 return bar();
3475 }
3476 </CODE_SNIPPET>
3477 <p>you can write this:</p>
3478 <CODE_SNIPPET>
3479 return val ? foo() : bar();
3480 </CODE_SNIPPET>
3481
3482 <p>The ternary conditional is also useful when generating HTML:</p>
3483 <CODE_SNIPPET>
3484 var html = '&lt;input type="checkbox"' +
3485 (isChecked ? ' checked' : '') +
3486 (isEnabled ? '' : ' disabled') +
3487 ' name="foo"&gt;';
3488 </CODE_SNIPPET>
3489 </SUBSECTION>
3490
3491 <SUBSECTION title="&amp;&amp; and ||">
3492 <p>These binary boolean operators are short-circuited, and evaluate
3493 to the last evaluated term.</p>
3494
3495 <p>"||" has been called the 'default' operator, because instead of
3496 writing this:</p>
3497 <BAD_CODE_SNIPPET>
3498 /** @param {*=} opt_win */
3499 function foo(opt_win) {
3500 var win;
3501 if (opt_win) {
3502 win = opt_win;
3503 } else {
3504 win = window;
3505 }
3506 // ...
3507 }
3508 </BAD_CODE_SNIPPET>
3509 <p>you can write this:</p>
3510 <CODE_SNIPPET>
3511 /** @param {*=} opt_win */
3512 function foo(opt_win) {
3513 var win = opt_win || window;
3514 // ...
3515 }
3516 </CODE_SNIPPET>
3517
3518 <p>"&amp;&amp;" is also useful for shortening code. For instance,
3519 instead of this:</p>
3520 <BAD_CODE_SNIPPET>
3521 if (node) {
3522 if (node.kids) {
3523 if (node.kids[index]) {
3524 foo(node.kids[index]);
3525 }
3526 }
3527 }
3528 </BAD_CODE_SNIPPET>
3529
3530 <p>you could do this:</p>
3531 <CODE_SNIPPET>
3532 if (node &amp;&amp; node.kids &amp;&amp; node.kids[index]) {
3533 foo(node.kids[index]);
3534 }
3535 </CODE_SNIPPET>
3536
3537 <p>or this:</p>
3538 <CODE_SNIPPET>
3539 var kid = node &amp;&amp; node.kids &amp;&amp; node.kids[index];
3540 if (kid) {
3541 foo(kid);
3542 }
3543 </CODE_SNIPPET>
3544
3545 <p>However, this is going a little too far:</p>
3546 <BAD_CODE_SNIPPET>
3547 node &amp;&amp; node.kids &amp;&amp; node.kids[index] &amp;&amp; foo(node.kids[index]);
3548 </BAD_CODE_SNIPPET>
3549 </SUBSECTION>
3550
robbyw@google.combb324012010-07-12 22:02:20 +00003551 <SUBSECTION title="Iterating over Node Lists">
3552 <p>Node lists are often implemented as node iterators with a filter.
3553 This means that getting a property like length is O(n), and
3554 iterating over the list by re-checking the length will be
3555 O(n^2).</p>
3556 <BAD_CODE_SNIPPET>
3557 var paragraphs = document.getElementsByTagName('p');
3558 for (var i = 0; i &lt; paragraphs.length; i++) {
3559 doSomething(paragraphs[i]);
3560 }
3561 </BAD_CODE_SNIPPET>
3562
3563 <p>It is better to do this instead:</p>
3564 <CODE_SNIPPET>
3565 var paragraphs = document.getElementsByTagName('p');
3566 for (var i = 0, paragraph; paragraph = paragraphs[i]; i++) {
3567 doSomething(paragraph);
3568 }
3569 </CODE_SNIPPET>
3570
3571 <p>This works well for all collections and arrays as long as the array
3572 does not contain things that are treated as boolean false.</p>
3573
3574 <p>In cases where you are iterating over the childNodes you can also
3575 use the firstChild and nextSibling properties.</p>
3576 <CODE_SNIPPET>
3577 var parentNode = document.getElementById('foo');
3578 for (var child = parentNode.firstChild; child; child = child.nextSibling) {
3579 doSomething(child);
3580 }
3581 </CODE_SNIPPET>
3582 </SUBSECTION>
3583 </BODY>
3584 </STYLEPOINT>
3585 </CATEGORY>
3586
3587
3588
3589 <PARTING_WORDS>
3590 <p>
3591 <em>BE CONSISTENT</em>.
3592 </p>
3593
3594 <p>
3595 If you're editing code, take a few minutes to look at the code
3596 around you and determine its style. If they use spaces around
3597 all their arithmetic operators, you should too. If their
3598 comments have little boxes of hash marks around them, make your
3599 comments have little boxes of hash marks around them too.
3600 </p>
3601
3602 <p>
3603 The point of having style guidelines is to have a common vocabulary
3604 of coding so people can concentrate on what you're saying rather
3605 than on how you're saying it. We present global style rules here so
3606 people know the vocabulary, but local style is also important. If
3607 code you add to a file looks drastically different from the existing
3608 code around it, it throws readers out of their rhythm when they go to
3609 read it. Avoid this.
3610 </p>
3611
3612 </PARTING_WORDS>
3613
3614 <p align="right">
mark@chromium.org7b245632013-09-25 21:16:00 +00003615 Revision 2.93
robbyw@google.combb324012010-07-12 22:02:20 +00003616 </p>
3617
3618
3619 <address>
3620 Aaron Whyte<br/>
3621 Bob Jervis<br/>
3622 Dan Pupius<br/>
3623 Erik Arvidsson<br/>
3624 Fritz Schneider<br/>
3625 Robby Walker<br/>
3626 </address>
3627</GUIDE>