From 8f254427d96220ce86250b0e55da09dfa082765d Mon Sep 17 00:00:00 2001 From: Stephen Hicks Date: Wed, 2 Nov 2016 17:17:28 -0700 Subject: [PATCH] Update and replace JavaScript style guide. The new guide is completely rewritten in light of ES2015. The old guide has been replaced with a link to the new guide. --- README.md | 2 +- angularjs-google-style.html | 8 +- include/jsguide.js | 56 + javascriptguide.xml | 3621 +---------------------------------- jsguide.html | 2650 +++++++++++++++++++++++++ 5 files changed, 2711 insertions(+), 3626 deletions(-) create mode 100644 include/jsguide.js create mode 100644 jsguide.html diff --git a/README.md b/README.md index 8dc482932..389771092 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ for more details. [r]: https://google.github.io/styleguide/Rguide.xml [sh]: https://google.github.io/styleguide/shell.xml [htmlcss]: https://google.github.io/styleguide/htmlcssguide.xml -[js]: https://google.github.io/styleguide/javascriptguide.xml +[js]: https://google.github.io/styleguide/jsguide.html [angular]: https://google.github.io/styleguide/angularjs-google-style.html [cl]: https://google.github.io/styleguide/lispguide.xml [vim]: https://google.github.io/styleguide/vimscriptguide.xml diff --git a/angularjs-google-style.html b/angularjs-google-style.html index 92b775f60..6bcd5d2a0 100644 --- a/angularjs-google-style.html +++ b/angularjs-google-style.html @@ -21,14 +21,14 @@

An AngularJS Style Guide for Closure Users at Google

(or not apply) these recommendations, as relevant to their own use cases.

This document describes style for AngularJS apps in google3. This guide - supplements and extends the + supplements and extends the Google JavaScript Style Guide.

Style Note: Examples on the AngularJS external webpage, and many external apps, are written in a style that freely uses closures, favors functional inheritance, and does not often use + href="https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System"> JavaScript types. Google follows a more rigorous Javascript style to support JSCompiler optimizations and large code bases - see the javascript-style mailing list. This is not an Angular-specific issue, and is not discussed further in this style guide. @@ -151,9 +151,7 @@

JSCompiler Flags

Controllers and Scopes

-

Controllers are classes. Methods should be defined on MyCtrl.prototype. - See - the JavaScript style guide

+

Controllers are classes. Methods should be defined on MyCtrl.prototype.

Google Angular applications should use the 'controller as' style to export the controller onto the scope. This is fully implemented in Angular 1.2 and can be mimicked in pre-Angular 1.2 diff --git a/include/jsguide.js b/include/jsguide.js new file mode 100644 index 000000000..dcf56898e --- /dev/null +++ b/include/jsguide.js @@ -0,0 +1,56 @@ +window.initStyleGuide = function(init) { + // Runs the callback on every element matched by the query selector. + function find(querySelector, callback) { + var elements = [].slice.call(document.querySelectorAll(querySelector)); + for (var i = 0; i < elements.length; i++) { + callback(elements[i]); + } + } + // Add the tocDiv at the top. + var title = document.getElementsByTagName('h1')[0]; + var toc = document.createElement('div'); + toc.id = 'tocDiv'; + toc.className = 'vertical_toc'; + title.parentNode.insertBefore(toc, title.nextSibling); + + // If a paragraph starts with (e.g.) "Note:" or "Tip:" then add + // that "callout class" to its element. + find('p', function(paragraph) { + var match = /^([a-z]+):/i.exec(paragraph.textContent); + if (match) { + paragraph.classList.add(match[1].toLowerCase()); + } + }); + + // Fill in text for intra-document links, ensuring that links + // remain up-to-date even if sections are moved or renumbered. + // This triggers on any link with "??" as its text and a URL + // starting with "#", and the filled-in text is exactly the same + // as the text of the referenced section heading. + find('a[href^="#"]', function(link) { + var href = link.getAttribute('href'); + var heading = document.getElementById(href.substring(1)); + // Fill in link text with heading title + if (heading && link.textContent == '??') { + link.textContent = heading.textContent; + } + }); + + // Hoedown renders fenced code blocks incompatibly with what + // prettify expects. As a result, prettify doesn't handle them + // properly. Fix it by moving the code directly into the pre. + find('pre > code', function(code) { + var pre = code.parentElement; + pre.className = code.className; + pre.innerHTML = code.innerHTML; + }); + + // Run the normal init function. + init(); + + // Call the pretty-printer after we've fixed up the code blocks. + var pretty = document.createElement('script'); + pretty.src = 'https://cdn.rawgit.com/google/code-prettify/master/loader/' + + 'run_prettify.js'; + document.body.appendChild(pretty); +}.bind(null, window.initStyleGuide); diff --git a/javascriptguide.xml b/javascriptguide.xml index c6696bc04..b56fca0a4 100644 --- a/javascriptguide.xml +++ b/javascriptguide.xml @@ -2,3625 +2,6 @@

- - Revision 2.93 + Please note: this guide has been updated and moved.

- -
- Aaron Whyte
- Bob Jervis
- Dan Pupius
- Erik Arvidsson
- Fritz Schneider
- Robby Walker
-
- - - - - This style guide contains many details that are initially - hidden from view. They are marked by the triangle icon, which you - see here on your left. Click it now. - You should see "Hooray" appear below. - - -

- Hooray! Now you know you can expand points to get more - details. Alternatively, there's a "toggle all" at the - top of this document. -

- -
-
- -

- JavaScript is the main client-side scripting language used - - by many of Google's open-source - projects. - This style guide is a list of dos and don'ts for - JavaScript programs. -

- - - - - -
-
- - - - - - - - Declarations with var: Always - - - - When you fail to specify var, - the variable gets placed in the global context, potentially clobbering - existing values. Also, if there's no declaration, it's hard to tell in - what scope a variable lives (e.g., it could be in the Document or - Window just as easily as in the local scope). So always declare with - var. - - - - - - -
    -
  • Use NAMES_LIKE_THIS for constant values.
  • -
  • Use @const to indicate a constant (non-overwritable) - pointer (a variable or property).
  • -
  • Never use the - - const keyword - as it's not supported in Internet Explorer.
  • -
-
- - - - -

If a value is intended to be constant - and immutable, it should be given a name - in CONSTANT_VALUE_CASE. - ALL_CAPS additionally implies @const - (that the value is not overwritable). -

- -

Primitive types (number, string, - boolean) are constant values.

- -

Objects' - immutability is more subjective — objects should be - considered immutable only if they do not demonstrate observable - state change. This is not enforced by the compiler.

- - -
- - -

The @const annotation on a variable or property - implies that it is not overwritable. This is enforced by the - compiler at build time. This behavior is consistent with the - - const keyword (which we do not use due to the - lack of support in Internet Explorer).

- -

A @const annotation on a method additionally - implies that the method cannot not be overridden in subclasses. -

- -

A @const annotation on a constructor implies the - class cannot be subclassed (akin to final in Java). -

- -
- - - -

Note that @const does not necessarily imply - CONSTANT_VALUES_CASE. - - However, CONSTANT_VALUES_CASE - does imply @const. -

- - - /** - * Request timeout in milliseconds. - * @type {number} - */ - goog.example.TIMEOUT_IN_MILLISECONDS = 60; - - -

The number of seconds in a minute never changes. It is a - constant value. ALL_CAPS - also implies @const, so the constant cannot be - overwritten. -

- -

The open source compiler will allow the symbol to be - overwritten because the constant is - not marked as @const.

- - - /** - * Map of URL to response string. - * @const - */ - MyClass.fetchedUrlCache_ = new goog.structs.Map(); - - - - /** - * Class that cannot be subclassed. - * @const - * @constructor - */ - sloth.MyFinalClass = function() {}; - - -

In this case, the pointer can never be overwritten, but - value is highly mutable and not constant (and thus in - camelCase, not ALL_CAPS).

-
- -
- -
- - - - Always use semicolons. - - -

Relying on implicit insertion can cause subtle, hard to debug - problems. Don't do it. You're better than that.

-

There are a couple places where missing semicolons are particularly - dangerous:

- - // 1. - MyClass.prototype.myMethod = function() { - return 42; - } // No semicolon here. - - (function() { - // Some initialization code wrapped in a function to create a scope for locals. - })(); - - - var x = { - 'i': 1, - 'j': 2 - } // No semicolon here. - - // 2. Trying to do one thing on Internet Explorer and another on Firefox. - // I know you'd never write code like this, but throw me a bone. - [ffVersion, ieVersion][isIE](); - - - var THINGS_TO_EAT = [apples, oysters, sprayOnCheese] // No semicolon here. - - // 3. conditional execution a la bash - -1 == resultOfOperation() || die(); - - -
    -
  1. JavaScript error - first the function returning 42 is called - with the second function as a parameter, then the number 42 is - "called" resulting in an error.
  2. -
  3. You will most likely get a 'no such property in undefined' - error at runtime as it tries to call - x[ffVersion, ieVersion][isIE]().
  4. -
  5. die is always called since the array minus 1 is - NaN which is never equal to anything (not even if - resultOfOperation() returns NaN) and - THINGS_TO_EAT gets assigned the result of - die().
  6. -
-
- -

JavaScript requires statements to end with a semicolon, except when - it thinks it can safely infer their existence. In each of these - examples, a function declaration or object or array literal is used - inside a statement. The closing brackets are not enough to signal - the end of the statement. Javascript never ends a statement if the - next token is an infix or bracket operator.

-

This has really surprised people, so make sure your assignments end - with semicolons.

-
- -

Semicolons should be included at the end of function expressions, - but not at the end of function declarations. The distinction is - best illustrated with an example:

- - var foo = function() { - return true; - }; // semicolon here. - - function foo() { - return true; - } // no semicolon here. - -
- -
- - - Yes - -

Nested functions can be very useful, for example in the creation of - continuations and for the task of hiding helper functions. Feel free - to use them.

- -
- - - No - -

Do not do this:

- - if (x) { - function foo() {} - } - - -

While most script engines support Function Declarations within blocks - it is not part of ECMAScript (see - ECMA-262, - clause 13 and 14). Worse implementations are inconsistent with each - other and with future EcmaScript proposals. ECMAScript only allows for - Function Declarations in the root statement list of a script or - function. Instead use a variable initialized with a Function - Expression to define a function within a block:

- - if (x) { - var foo = function() {}; - } - - -
- - - Yes - -

You basically can't avoid exceptions if you're doing something - non-trivial (using an application development framework, etc.). - Go for it.

- -
- - - Yes - -

Without custom exceptions, returning error information from a - function that also returns a value can be tricky, not to mention - inelegant. Bad solutions include passing in a reference type to hold - error information or always returning Objects with a potential - error member. These basically amount to a primitive exception - handling hack. Feel free to use custom exceptions when - appropriate.

- -
- - - Always preferred over non-standards features - -

For maximum portability and compatibility, always prefer standards - features over non-standards features (e.g., - string.charAt(3) over string[3] and element - access with DOM functions instead of using an application-specific - shorthand).

- -
- - - No - -

There's no reason to use wrapper objects for primitive types, plus - they're dangerous:

- - var x = new Boolean(false); - if (x) { - alert('hi'); // Shows 'hi'. - } - -

Don't do it!

-

However type casting is fine.

- - var x = Boolean(0); - if (x) { - alert('hi'); // This will never be alerted. - } - typeof Boolean(0) == 'boolean'; - typeof new Boolean(0) == 'object'; - -

This is very useful for casting things to - number, string and boolean.

- -
- - - Not preferred - -

Multi-level prototype hierarchies are how JavaScript implements - inheritance. You have a multi-level hierarchy if you have a - user-defined class D with another user-defined class B as its - prototype. These hierarchies are much harder to get right than they - first appear!

- -

For that reason, it is best to use goog.inherits() from - - the Closure Library - - or a similar library function. -

- - function D() { - goog.base(this) - } - goog.inherits(D, B); - - D.prototype.method = function() { - ... - }; - - -
- - - /** @constructor */ - function SomeConstructor() { - this.someProperty = 1; - } - Foo.prototype.someMethod = function() { ... }; - -

While there are several ways to attach methods and properties to an - object created via "new", the preferred style for methods - is:

- - Foo.prototype.bar = function() { - /* ... */ - }; - -

The preferred style for other properties is to initialize the field - in the constructor:

- - /** @constructor */ - function Foo() { - this.bar = value; - } - - -

Current JavaScript engines optimize based on the "shape" - of an object, - adding a property to an object (including overriding - a value set on the prototype) changes the shape and can degrade - performance.

-
- -
- - - Prefer this.foo = null. - - - Foo.prototype.dispose = function() { - this.property_ = null; - }; - -

Instead of:

- - Foo.prototype.dispose = function() { - delete this.property_; - }; - -

In modern JavaScript engines, changing the number of properties on an - object is much slower than reassigning the values. The delete keyword - should be avoided except when it is necessary to remove a property - from an object's iterated list of keys, or to change the result of - if (key in obj).

- -
- - - Yes, but be careful. - -

The ability to create closures is perhaps the most useful and often - overlooked feature of JS. Here is - - a good description of how closures work.

-

One thing to keep in mind, however, is that a closure keeps a pointer - to its enclosing scope. As a result, attaching a closure to a DOM - element can create a circular reference and thus, a memory leak. For - example, in the following code:

- - function foo(element, a, b) { - element.onclick = function() { /* uses a and b */ }; - } - -

the function closure keeps a reference to element, - a, and b even if it never uses - element. Since element also keeps a - reference to the closure, we have a cycle that won't be cleaned up by - garbage collection. In these situations, the code can be structured - as follows:

- - function foo(element, a, b) { - element.onclick = bar(a, b); - } - - function bar(a, b) { - return function() { /* uses a and b */ }; - } - - -
- - - - Only for code loaders and REPL (Read–eval–print loop) - - -

eval() makes for confusing semantics and is dangerous - to use if the string being eval()'d contains user input. - There's usually a better, clearer, and safer way to write your code, - so its use is generally not permitted.

- -

For RPC you can always use JSON and read the result using - JSON.parse() instead of eval().

- -

Let's assume we have a server that returns something like this:

- - - { - "name": "Alice", - "id": 31502, - "email": "looking_glass@example.com" - } - - - - var userInfo = eval(feed); - var email = userInfo['email']; - - -

If the feed was modified to include malicious JavaScript code, then - if we use eval then that code will be executed.

- - - var userInfo = JSON.parse(feed); - var email = userInfo['email']; - - -

With JSON.parse, invalid JSON (including all executable - JavaScript) will cause an exception to be thrown.

- - -
- - - No - -

Using with clouds the semantics of your program. - Because the object of the with can have properties that - collide with local variables, it can drastically change the meaning - of your program. For example, what does this do?

- - with (foo) { - var x = 3; - return x; - } - -

Answer: anything. The local variable x could be - clobbered by a property of foo and perhaps it even has - a setter, in which case assigning 3 could cause lots of - other code to execute. Don't use with.

- -
- - - - Only in object constructors, methods, and in setting up closures - - -

The semantics of this can be tricky. At times it refers - to the global object (in most places), the scope of the caller (in - eval), a node in the DOM tree (when attached using an - event handler HTML attribute), a newly created object (in a - constructor), or some other object (if function was - call()ed or apply()ed).

-

Because this is so easy to get wrong, limit its use to those places - where it is required:

-
    -
  • in constructors
  • -
  • in methods of objects (including in the creation of closures)
  • -
- -
- - - - Only for iterating over keys in an object/map/hash - - -

for-in loops are often incorrectly used to loop over - the elements in an Array. This is however very error - prone because it does not loop from 0 to - length - 1 but over all the present keys in the object - and its prototype chain. Here are a few cases where it fails:

- - function printArray(arr) { - for (var key in arr) { - print(arr[key]); - } - } - - printArray([0,1,2,3]); // This works. - - var a = new Array(10); - printArray(a); // This is wrong. - - a = document.getElementsByTagName('*'); - printArray(a); // This is wrong. - - a = [0,1,2,3]; - a.buhu = 'wine'; - printArray(a); // This is wrong again. - - a = new Array; - a[3] = 3; - printArray(a); // This is wrong again. - -

Always use normal for loops when using arrays.

- - function printArray(arr) { - var l = arr.length; - for (var i = 0; i < l; i++) { - print(arr[i]); - } - } - - -
- - - - Never use Array as a map/hash/associative array - - -

Associative Arrays are not allowed... or more precisely - you are not allowed to use non number indexes for arrays. If you need - a map/hash use Object instead of Array in - these cases because the features that you want are actually features - of Object and not of Array. - Array just happens to extend Object (like - any other object in JS and therefore you might as well have used - Date, RegExp or String).

- -
- - - No - -

Do not do this:

- - var myString = 'A rather long string of English text, an error message \ - actually that just keeps going and going -- an error \ - message to make the Energizer bunny blush (right through \ - those Schwarzenegger shades)! Where was I? Oh yes, \ - you\'ve got an error and all the extraneous whitespace is \ - just gravy. Have a nice day.'; - -

The whitespace at the beginning of each line can't be safely stripped - at compile time; whitespace after the slash will result in tricky - errors.

-

Use string concatenation instead:

- - var myString = 'A rather long string of English text, an error message ' + - 'actually that just keeps going and going -- an error ' + - 'message to make the Energizer bunny blush (right through ' + - 'those Schwarzenegger shades)! Where was I? Oh yes, ' + - 'you\'ve got an error and all the extraneous whitespace is ' + - 'just gravy. Have a nice day.'; - - -
- - - Yes - -

Use Array and Object literals instead of - Array and Object constructors.

-

Array constructors are error-prone due to their arguments.

- - // Length is 3. - var a1 = new Array(x1, x2, x3); - - // Length is 2. - var a2 = new Array(x1, x2); - - // If x1 is a number and it is a natural number the length will be x1. - // If x1 is a number but not a natural number this will throw an exception. - // Otherwise the array will have one element with x1 as its value. - var a3 = new Array(x1); - - // Length is 0. - var a4 = new Array(); - -

Because of this, if someone changes the code to pass 1 argument - instead of 2 arguments, the array might not have the expected - length.

-

To avoid these kinds of weird cases, always use the more readable - array literal.

- - var a = [x1, x2, x3]; - var a2 = [x1, x2]; - var a3 = [x1]; - var a4 = []; - -

Object constructors don't have the same problems, but for readability - and consistency object literals should be used.

- - var o = new Object(); - - var o2 = new Object(); - o2.a = 0; - o2.b = 1; - o2.c = 2; - o2['strange key'] = 3; - -

Should be written as:

- - var o = {}; - - var o2 = { - a: 0, - b: 1, - c: 2, - 'strange key': 3 - }; - - -
- - - No - -

Modifying builtins like Object.prototype and - Array.prototype are strictly forbidden. Modifying other - builtins like Function.prototype is less dangerous but - still leads to hard to debug issues in production and should be - avoided.

- -
- - - No - -

Don't do this:

- - var f = function () { - /*@cc_on if (@_jscript) { return 2* @*/ 3; /*@ } @*/ - }; - -

Conditional Comments hinder automated tools as they can vary the - JavaScript syntax tree at runtime.

- -
-
- - - - -

In general, use - functionNamesLikeThis, - variableNamesLikeThis, - ClassNamesLikeThis, - EnumNamesLikeThis, - methodNamesLikeThis, - CONSTANT_VALUES_LIKE_THIS, - foo.namespaceNamesLikeThis.bar, and - filenameslikethis.js. -

-
- - -
    -
  • Private properties and methods should be named with a - trailing underscore. -
  • -
  • Protected properties and methods should be - named without a trailing underscore (like public ones).
  • -
-

For more information on private and protected, - read the section on - - visibility. -

- - - - -
- - -

Optional function arguments start with opt_.

-

Functions that take a variable number of arguments should have the - last argument named var_args. You may not refer to - var_args in the code; use the arguments - array.

-

Optional and variable arguments can also be specified in - @param annotations. Although either convention is - acceptable to the compiler, using both together is preferred.

- -
- - -

EcmaScript 5 getters and setters for properties are discouraged. - However, if they are used, then getters must not change observable - state.

- - /** - * WRONG -- Do NOT do this. - */ - var foo = { get next() { return this.nextId++; } }; - -
- - -

Getters and setters methods for properties are not required. - However, if they are used, then getters must be named - getFoo() and setters must be named - setFoo(value). (For boolean getters, - isFoo() is also acceptable, and often sounds more - natural.)

-
- - -

JavaScript has no inherent packaging or namespacing support.

-

Global name conflicts are difficult to debug, and can cause - intractable problems when two projects try to integrate. In order - to make it possible to share common JavaScript code, we've adopted - conventions to prevent collisions.

- -

ALWAYS prefix identifiers in the global scope with a - unique pseudo namespace related to the project or library. If you - are working on "Project Sloth", a reasonable pseudo namespace - would be sloth.*.

- - var sloth = {}; - - sloth.sleep = function() { - ... - }; - - - -

Many JavaScript libraries, including - - the Closure Library - - and - - Dojo toolkit - - give you high-level functions for declaring your namespaces. - Be consistent about how you declare your namespaces.

- - goog.provide('sloth'); - - sloth.sleep = function() { - ... - }; - -
- -

When choosing a child-namespace, make sure that the owners of the - parent namespace know what you are doing. If you start a project - that creates hats for sloths, make sure that the Sloth team knows - that you're using sloth.hats.

- -
- -

"External code" is code that comes from outside your codebase, - and is compiled independently. Internal and external names should - be kept strictly separate. If you're using an external library - that makes things available in foo.hats.*, your - internal code should not define all its symbols in - foo.hats.*, because it will break if the other - team defines new symbols.

- - foo.require('foo.hats'); - - /** - * WRONG -- Do NOT do this. - * @constructor - * @extends {foo.hats.RoundHat} - */ - foo.hats.BowlerHat = function() { - }; - -

If you need to define new APIs on an external namespace, then you - should explicitly export the public API functions, and only those - functions. Your internal code should call the internal APIs by - their internal names, for consistency and so that the compiler - can optimize them better.

- - foo.provide('googleyhats.BowlerHat'); - - foo.require('foo.hats'); - - /** - * @constructor - * @extends {foo.hats.RoundHat} - */ - googleyhats.BowlerHat = function() { - ... - }; - - goog.exportSymbol('foo.hats.BowlerHat', googleyhats.BowlerHat); - - - -
- -

Use local aliases for fully-qualified types if doing so improves - readability. The name of a local alias should match the last part - of the type.

- - /** - * @constructor - */ - some.long.namespace.MyClass = function() { - }; - - /** - * @param {some.long.namespace.MyClass} a - */ - some.long.namespace.MyClass.staticHelper = function(a) { - ... - }; - - myapp.main = function() { - var MyClass = some.long.namespace.MyClass; - var staticHelper = some.long.namespace.MyClass.staticHelper; - staticHelper(new MyClass()); - }; - -

Do not create local aliases of namespaces. Namespaces should only - be aliased using goog.scope.

- - myapp.main = function() { - var namespace = some.long.namespace; - namespace.MyClass.staticHelper(new namespace.MyClass()); - }; - -

Avoid accessing properties of an aliased type, unless it is an - enum.

- - /** @enum {string} */ - some.long.namespace.Fruit = { - APPLE: 'a', - BANANA: 'b' - }; - - myapp.main = function() { - var Fruit = some.long.namespace.Fruit; - switch (fruit) { - case Fruit.APPLE: - ... - case Fruit.BANANA: - ... - } - }; - - - myapp.main = function() { - var MyClass = some.long.namespace.MyClass; - MyClass.staticHelper(null); - }; - -

Never create aliases in the global scope. Use them only in - function blocks.

-
-
- -

Filenames should be all lowercase in order to avoid confusion on - case-sensitive platforms. Filenames should end in .js, - and should contain no punctuation except for - or - _ (prefer - to _).

-
- - -
- - - - Must always succeed without side effects. - - -

You can control how your objects string-ify themselves by defining a - custom toString() method. This is fine, but you need - to ensure that your method (1) always succeeds and (2) does not have - side-effects. If your method doesn't meet these criteria, it's very - easy to run into serious problems. For example, if - toString() calls a method that does an - assert, assert might try to output the name - of the object in which it failed, which of course requires calling - toString().

- -
- - - OK - -

It isn't always possible to initialize variables at the point of - declaration, so deferred initialization is fine.

- -
- - - Always - -

Always use explicit scope - doing so increases portability and - clarity. For example, don't rely on window being in the - scope chain. You might want to use your function in another - application for which window is not the content - window.

- -
- - - Expand for more information. - -

We follow the C++ formatting - rules in spirit, with the following additional clarifications.

- -

Because of implicit semicolon insertion, always start your curly - braces on the same line as whatever they're opening. For - example:

- - if (something) { - // ... - } else { - // ... - } - -
- -

Single-line array and object initializers are allowed when they - fit on a line:

- - var arr = [1, 2, 3]; // No space after [ or before ]. - var obj = {a: 1, b: 2, c: 3}; // No space after { or before }. - -

Multiline array initializers and object initializers are indented - 2 spaces, with the braces on their own line, just like blocks.

- - // Object initializer. - var inset = { - top: 10, - right: 20, - bottom: 15, - left: 12 - }; - - // Array initializer. - this.rows_ = [ - '"Slartibartfast" <fjordmaster@magrathea.com>', - '"Zaphod Beeblebrox" <theprez@universe.gov>', - '"Ford Prefect" <ford@theguide.com>', - '"Arthur Dent" <has.no.tea@gmail.com>', - '"Marvin the Paranoid Android" <marv@googlemail.com>', - 'the.mice@magrathea.com' - ]; - - // Used in a method call. - goog.dom.createDom(goog.dom.TagName.DIV, { - id: 'foo', - className: 'some-css-class', - style: 'display:none' - }, 'Hello, world!'); - -

Long identifiers or values present problems for aligned - initialization lists, so always prefer non-aligned initialization. - For example:

- - CORRECT_Object.prototype = { - a: 0, - b: 1, - lengthyName: 2 - }; - -

Not like this:

- - WRONG_Object.prototype = { - a : 0, - b : 1, - lengthyName: 2 - }; - -
- -

When possible, all function arguments should be listed on the same - line. If doing so would exceed the 80-column limit, the arguments - must be line-wrapped in a readable way. To save space, you may wrap - as close to 80 as possible, or put each argument on its own line to - enhance readability. The indentation may be either four spaces, or - aligned to the parenthesis. Below are the most common patterns for - argument wrapping:

- - // Four-space, wrap at 80. Works with very long function names, survives - // renaming without reindenting, low on space. - goog.foo.bar.doThingThatIsVeryDifficultToExplain = function( - veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo, - tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) { - // ... - }; - - // Four-space, one argument per line. Works with long function names, - // survives renaming, and emphasizes each argument. - goog.foo.bar.doThingThatIsVeryDifficultToExplain = function( - veryDescriptiveArgumentNumberOne, - veryDescriptiveArgumentTwo, - tableModelEventHandlerProxy, - artichokeDescriptorAdapterIterator) { - // ... - }; - - // Parenthesis-aligned indentation, wrap at 80. Visually groups arguments, - // low on space. - function foo(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo, - tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) { - // ... - } - - // Parenthesis-aligned, one argument per line. Emphasizes each - // individual argument. - function bar(veryDescriptiveArgumentNumberOne, - veryDescriptiveArgumentTwo, - tableModelEventHandlerProxy, - artichokeDescriptorAdapterIterator) { - // ... - } - -

When the function call is itself indented, you're free to start the - 4-space indent relative to the beginning of the original statement - or relative to the beginning of the current function call. - The following are all acceptable indentation styles.

- - if (veryLongFunctionNameA( - veryLongArgumentName) || - veryLongFunctionNameB( - veryLongArgumentName)) { - veryLongFunctionNameC(veryLongFunctionNameD( - veryLongFunctioNameE( - veryLongFunctionNameF))); - } - -
- -

When declaring an anonymous function in the list of arguments for - a function call, the body of the function is indented two spaces - from the left edge of the statement, or two spaces from the left - edge of the function keyword. This is to make the body of the - anonymous function easier to read (i.e. not be all squished up into - the right half of the screen).

- - prefix.something.reallyLongFunctionName('whatever', function(a1, a2) { - if (a1.equals(a2)) { - someOtherLongFunctionName(a1); - } else { - andNowForSomethingCompletelyDifferent(a2.parrot); - } - }); - - var names = prefix.something.myExcellentMapFunction( - verboselyNamedCollectionOfItems, - function(item) { - return item.name; - }); - -
- - -

- goog.scope - may be used to shorten references to - namespaced symbols in programs using - the Closure - Library.

-

Only one goog.scope invocation may be added per - file. Always place it in the global scope.

-

The opening goog.scope(function() { invocation - must be preceded by exactly one blank line and follow any - goog.provide statements, goog.require - statements, or top-level comments. The invocation must be closed on - the last line in the file. Append // goog.scope to the - closing statement of the scope. Separate the comment from the - semicolon by two spaces.

-

Similar to C++ namespaces, do not indent under goog.scope - declarations. Instead, continue from the 0 column.

-

Only alias names that will not be re-assigned to another object - (e.g., most constructors, enums, and namespaces). Do not do - this (see below for how to alias a constructor):

- - - goog.scope(function() { - var Button = goog.ui.Button; - - Button = function() { ... }; - ... - - -

Names must be the same as the last property of the global that they - are aliasing.

- - - goog.provide('my.module.SomeType'); - - goog.require('goog.dom'); - goog.require('goog.ui.Button'); - - goog.scope(function() { - var Button = goog.ui.Button; - var dom = goog.dom; - - // Alias new types after the constructor declaration. - my.module.SomeType = function() { ... }; - var SomeType = my.module.SomeType; - - // Declare methods on the prototype as usual: - SomeType.prototype.findButton = function() { - // Button as aliased above. - this.button = new Button(dom.getElement('my-button')); - }; - ... - }); // goog.scope - -
- -

Except for array literals, - object literals, and anonymous functions, all wrapped lines - should be indented either left-aligned to a sibling expression - above, or four spaces (not two spaces) deeper than a parent - expression (where "sibling" and "parent" refer to parenthesis - nesting level). -

- - - someWonderfulHtml = '
' + - getEvenMoreHtml(someReallyInterestingValues, moreValues, - evenMoreParams, 'a duck', true, 72, - slightlyMoreMonkeys(0xfff)) + - '
'; - - thisIsAVeryLongVariableName = - hereIsAnEvenLongerOtherFunctionNameThatWillNotFitOnPrevLine(); - - thisIsAVeryLongVariableName = siblingOne + siblingTwo + siblingThree + - siblingFour + siblingFive + siblingSix + siblingSeven + - moreSiblingExpressions + allAtTheSameIndentationLevel; - - thisIsAVeryLongVariableName = operandOne + operandTwo + operandThree + - operandFour + operandFive * ( - aNestedChildExpression + shouldBeIndentedMore); - - someValue = this.foo( - shortArg, - 'Some really long string arg - this is a pretty common case, actually.', - shorty2, - this.bar()); - - if (searchableCollection(allYourStuff).contains(theStuffYouWant) && - !ambientNotification.isActive() && (client.isAmbientSupported() || - client.alwaysTryAmbientAnyways())) { - ambientNotification.activate(); - } -
-
- -

Use newlines to group logically related pieces of code. - For example:

- - doSomethingTo(x); - doSomethingElseTo(x); - andThen(x); - - nowDoSomethingWith(y); - - andNowWith(z); - -
- -

Always put the operator on the preceding line. Otherwise, - line breaks and indentation follow the same rules as in other - Google style guides. This operator placement was initially agreed - upon out of concerns about automatic semicolon insertion. In fact, - semicolon insertion cannot happen before a binary operator, but new - code should stick to this style for consistency.

- - var x = a ? b : c; // All on one line if it will fit. - - // Indentation +4 is OK. - var y = a ? - longButSimpleOperandB : longButSimpleOperandC; - - // Indenting to the line position of the first operand is also OK. - var z = a ? - moreComplicatedB : - moreComplicatedC; - -

This includes the dot operator.

- - var x = foo.bar(). - doSomething(). - doSomethingElse(); - -
- -
- - - Only where required - -

Use sparingly and in general only where required by the syntax - and semantics.

-

Never use parentheses for unary operators such as - delete, typeof and void or - after keywords such as return, throw as - well as others (case, in or - new).

- -
- - - Prefer ' over " - -

For consistency single-quotes (') are preferred to double-quotes ("). - This is helpful when creating strings that include HTML:

- - var msg = 'This is some HTML'; - - -
- - - Encouraged, use JSDoc annotations @private and - @protected - -

We recommend the use of the JSDoc annotations @private and - @protected to indicate visibility levels for classes, - functions, and properties.

-

The --jscomp_warning=visibility compiler flag turns on compiler - warnings for visibility violations. See - - Closure Compiler - Warnings. -

-

@private global variables and functions are only - accessible to code in the same file.

-

Constructors marked @private may only be instantiated by - code in the same file and by their static and instance members. - @private constructors may also be accessed anywhere in the - same file for their public static properties and by the - instanceof operator.

-

Global variables, functions, and constructors should never be - annotated @protected.

- - // File 1. - // AA_PrivateClass_ and AA_init_ are accessible because they are global - // and in the same file. - - /** - * @private - * @constructor - */ - AA_PrivateClass_ = function() { - }; - - /** @private */ - function AA_init_() { - return new AA_PrivateClass_(); - } - - AA_init_(); - -

@private properties are accessible to all code in the - same file, plus all static methods and instance methods of that class - that "owns" the property, if the property belongs to a class. They - cannot be accessed or overridden from a subclass in a different file.

-

@protected properties are accessible to all code in the - same file, plus any static methods and instance methods of any subclass - of a class that "owns" the property.

-

Note that these semantics differ from those of C++ and Java, in that - they grant private and protected access to all code in the same file, - not just in the same class or class hierarchy. Also, unlike in C++, - private properties cannot be overridden by a subclass. -

- - // File 1. - - /** @constructor */ - AA_PublicClass = function() { - /** @private */ - this.privateProp_ = 2; - - /** @protected */ - this.protectedProp = 4; - }; - - /** @private */ - AA_PublicClass.staticPrivateProp_ = 1; - - /** @protected */ - AA_PublicClass.staticProtectedProp = 31; - - /** @private */ - AA_PublicClass.prototype.privateMethod_ = function() {}; - - /** @protected */ - AA_PublicClass.prototype.protectedMethod = function() {}; - - // File 2. - - /** - * @return {number} The number of ducks we've arranged in a row. - */ - AA_PublicClass.prototype.method = function() { - // Legal accesses of these two properties. - return this.privateProp_ + AA_PublicClass.staticPrivateProp_; - }; - - // File 3. - - /** - * @constructor - * @extends {AA_PublicClass} - */ - AA_SubClass = function() { - // Legal access of a protected static property. - AA_PublicClass.staticProtectedProp = this.method(); - }; - goog.inherits(AA_SubClass, AA_PublicClass); - - /** - * @return {number} The number of ducks we've arranged in a row. - */ - AA_SubClass.prototype.method = function() { - // Legal access of a protected instance property. - return this.protectedProp; - }; - - -

Notice that in JavaScript, there is no distinction between a type - (like AA_PrivateClass_) and the constructor for that - type. There is no way to express both that a type is public and its - constructor is private (because the constructor could easily be aliased - in a way that would defeat the privacy check).

- -
- - - Encouraged and enforced by the compiler. - - -

When documenting a type in JSDoc, be as specific and accurate as - possible. The types we support are based on the - - EcmaScript 4 spec.

- -

The ES4 proposal contained a language for specifying JavaScript - types. We use this language in JsDoc to express the types of - function parameters and return values.

- -

As the ES4 proposal has evolved, this language has changed. The - compiler still supports old syntaxes for types, but those syntaxes - are deprecated.

- -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Syntax NameSyntaxDescriptionDeprecated Syntaxes
Primitive Type - There are 5 primitive types in JavaScript: - {null}, - {undefined}, - {boolean}, - {number}, and - {string}. - Simply the name of a type. -
Instance Type - {Object}
- An instance of Object or null.

- {Function}
- An instance of Function or null.

- {EventTarget}
- An instance of a constructor that implements the EventTarget - interface, or null. -

An instance of a constructor or interface function.

- - Constructor functions are functions defined with the - @constructor JSDoc tag. - Interface functions are functions defined with the - @interface JSDoc tag.

- - By default, instance types will accept null. This is the only - type syntax that makes the type nullable. Other type syntaxes - in this table will not accept null. -

-
Enum Type - {goog.events.EventType}
- One of the properties of the object literal initializer - of goog.events.EventType. -
An enum must be initialized as an object literal, or as - an alias of another enum, annotated with the @enum - JSDoc tag. The properties of this literal are the instances - of the enum. The syntax of the enum is defined - below.

- - Note that this is one of the few things in our type system - that were not in the ES4 spec. -

-
Type Application - {Array.<string>}
An array of strings.

- {Object.<string, number>} -
An object in which the keys are strings and the values - are numbers. -

Parameterizes a type, by applying a set of type arguments - to that type. The idea is analogous to generics in Java. - -
Type Union - {(number|boolean)}
A number or a boolean. -
Indicates that a value might have type A OR type B.

- - The parentheses may be omitted at the top-level - expression, but the parentheses should be included in - sub-expressions to avoid ambiguity.
- {number|boolean}
- {function(): (number|boolean)} -

- {(number,boolean)},
- {(number||boolean)} -
Nullable type - {?number}
A number or null. -
Shorthand for the union of the null type with any - other type. This is just syntactic sugar. - - {number?} -
Non-nullable type - {!Object}
An Object, but never the - null value. -
Filters null out of nullable types. Most often used - with instance types, which are nullable by default. - - {Object!} -
Record Type - {{myNum: number, myObject}} -
An anonymous type with the given type members. -
-

Indicates that the value has the specified members with the - specified types. In this case, myNum with a - type number and myObject with any - type.

-

Notice that the braces are part of the type syntax. For - example, to denote an Array of objects that - have a length property, you might write - Array.<{length}>.

-
-
Function Type - {function(string, boolean)}
- A function that takes two arguments (a string and a boolean), - and has an unknown return value.
-
Specifies a function. -
Function Return Type - {function(): number}
- A function that takes no arguments and returns a number.
-
Specifies a function return type. -
Function this Type - {function(this:goog.ui.Menu, string)}
- A function that takes one argument (a string), and executes - in the context of a goog.ui.Menu. -
Specifies the context type of a function type. -
Function new Type - {function(new:goog.ui.Menu, string)}
- A constructor that takes one argument (a string), and - creates a new instance of goog.ui.Menu when called - with the 'new' keyword. -
Specifies the constructed type of a constructor. -
Variable arguments - {function(string, ...[number]): number}
- A function that takes one argument (a string), and then a - variable number of arguments that must be numbers. -
Specifies variable arguments to a function. -
- - Variable arguments (in @param annotations) - - @param {...number} var_args
- A variable number of arguments to an annotated function. -
- Specifies that the annotated function accepts a variable - number of arguments. - -
Function optional arguments - {function(?string=, number=)}
- A function that takes one optional, nullable string and one - optional number as arguments. The = syntax is - only for function type declarations. -
Specifies optional arguments to a function. -
- - Function optional arguments - (in @param annotations) - - @param {number=} opt_argument
- An optional parameter of type number. -
Specifies that the annotated function accepts an optional - argument. -
The ALL type{*}Indicates that the variable can take on any type. -
The UNKNOWN type{?}Indicates that the variable can take on any type, - and the compiler should not type-check any uses of it. -
- - -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Type ExampleValue ExamplesDescription
number - - 1 - 1.0 - -5 - 1e5 - Math.PI - - -
Number - - new Number(true) - - - - Number object - -
string - - 'Hello' - "World" - String(42) - - - String value -
String - - new String('Hello') - new String(42) - - - - String object - -
boolean - - true - false - Boolean(0) - - - Boolean value -
Boolean - - new Boolean(true) - - - - Boolean object - -
RegExp - - new RegExp('hello') - /world/g - -
Date - - new Date - new Date() - -
- - null - - - - null - - -
- - undefined - - - - undefined - - -
void - - function f() { - return; - } - - No return value
Array - - ['foo', 0.3, null] - [] - - Untyped Array
Array.<number> - - [11, 22, 33] - - - An Array of numbers -
Array.<Array.<string>> - - [['one', 'two', 'three'], ['foo', 'bar']] - - Array of Arrays of strings
Object - - {} - {foo: 'abc', bar: 123, baz: null} - - -
Object.<string> - - {'foo': 'bar'} - - - An Object in which the values are strings. -
Object.<number, string> - - var obj = {}; - obj[1] = 'bar'; - - - An Object in which the keys are numbers and the values are - strings.

Note that in JavaScript, the keys are always - implicitly converted to strings, so - obj['1'] == obj[1]. - So the key will always be a string in for...in loops. But the - compiler will verify the type of the key when indexing into - the object. -

Function - - function(x, y) { - return x * y; - } - - - - Function object - -
function(number, number): number - - function(x, y) { - return x * y; - } - - function value
SomeClass - - /** @constructor */ - function SomeClass() {} - - new SomeClass(); - - -
SomeInterface - - /** @interface */ - function SomeInterface() {} - - SomeInterface.prototype.draw = function() {}; - - -
project.MyClass - - /** @constructor */ - project.MyClass = function () {} - - new project.MyClass() - - -
project.MyEnum - - /** @enum {string} */ - project.MyEnum = { - /** The color blue. */ - BLUE: '#0000dd', - /** The color red. */ - RED: '#dd0000' - }; - - Enumeration

- JSDoc comments on enum values are optional. -

Element - - document.createElement('div') - - Elements in the DOM.
Node - - document.body.firstChild - - Nodes in the DOM.
HTMLInputElement - - htmlDocument.getElementsByTagName('input')[0] - - A specific type of DOM element.
- - - -

In cases where type-checking doesn't accurately infer the type of - an expression, it is possible to add a type cast comment by adding a - type annotation comment and enclosing the expression in - parentheses. The parentheses are required.

- - - /** @type {number} */ (x) - -
- - - -

Because JavaScript is a loosely-typed language, it is very - important to understand the subtle differences between optional, - nullable, and undefined function parameters and class - properties.

- -

Instances of classes and interfaces are nullable by default. - For example, the following declaration

- - - /** - * Some class, initialized with a value. - * @param {Object} value Some value. - * @constructor - */ - function MyClass(value) { - /** - * Some value. - * @type {Object} - * @private - */ - this.myValue_ = value; - } - - -

tells the compiler that the myValue_ property holds - either an Object or null. If myValue_ must never be - null, it should be declared like this:

- - - /** - * Some class, initialized with a non-null value. - * @param {!Object} value Some value. - * @constructor - */ - function MyClass(value) { - /** - * Some value. - * @type {!Object} - * @private - */ - this.myValue_ = value; - } - - -

This way, if the compiler can determine that somewhere in the code - MyClass is initialized with a null value, it will issue - a warning.

- - - -

Optional parameters to functions may be undefined at runtime, so if - they are assigned to class properties, those properties must be - declared accordingly:

- - - /** - * Some class, initialized with an optional value. - * @param {Object=} opt_value Some value (optional). - * @constructor - */ - function MyClass(opt_value) { - /** - * Some value. - * @type {Object|undefined} - * @private - */ - this.myValue_ = opt_value; - } - - -

This tells the compiler that myValue_ may hold an - Object, null, or remain undefined.

- -

Note that the optional parameter opt_value is declared - to be of type {Object=}, not - {Object|undefined}. This is because optional - parameters may, by definition, be undefined. While there is no harm - in explicitly declaring an optional parameter as possibly undefined, - it is both unnecessary and makes the code harder to read.

- -

Finally, note that being nullable and being optional are orthogonal - properties. The following four declarations are all different:

- - - /** - * Takes four arguments, two of which are nullable, and two of which are - * optional. - * @param {!Object} nonNull Mandatory (must not be undefined), must not be null. - * @param {Object} mayBeNull Mandatory (must not be undefined), may be null. - * @param {!Object=} opt_nonNull Optional (may be undefined), but if present, - * must not be null! - * @param {Object=} opt_mayBeNull Optional (may be undefined), may be null. - */ - function strangeButTrue(nonNull, mayBeNull, opt_nonNull, opt_mayBeNull) { - // ... - }; - -
- - - -

Sometimes types can get complicated. A function that accepts - content for an Element might look like:

- - - /** - * @param {string} tagName - * @param {(string|Element|Text|Array.<Element>|Array.<Text>)} contents - * @return {!Element} - */ - goog.createElement = function(tagName, contents) { - ... - }; - - -

You can define commonly used type expressions with a - @typedef tag. For example,

- - - /** @typedef {(string|Element|Text|Array.<Element>|Array.<Text>)} */ - goog.ElementContent; - - /** - * @param {string} tagName - * @param {goog.ElementContent} contents - * @return {!Element} - */ - goog.createElement = function(tagName, contents) { - ... - }; - - - - -
-

The compiler has limited support for template types. It can only - infer the type of this inside an anonymous function - literal from the type of the this argument and whether the - this argument is missing.

- - - /** - * @param {function(this:T, ...)} fn - * @param {T} thisObj - * @param {...*} var_args - * @template T - */ - goog.bind = function(fn, thisObj, var_args) { - ... - }; - // Possibly generates a missing property warning. - goog.bind(function() { this.someProperty; }, new SomeClass()); - // Generates an undefined this warning. - goog.bind(function() { this.someProperty; }); - - - -
- - - Use JSDoc - -

- We follow the - - C++ style for comments in spirit. -

- -

All files, classes, methods and properties should be documented with - JSDoc - comments with the appropriate tags - and types. Textual descriptions for properties, - methods, method parameters and method return values should be included - unless obvious from the property, method, or parameter name. -

- -

Inline comments should be of the // variety.

- -

Complete sentences are recommended but not required. - Complete sentences should use appropriate capitalization - and punctuation.

- - -

The JSDoc syntax is based on - - JavaDoc. Many tools extract metadata from JSDoc comments to - perform code validation and optimizations. These comments must be - well-formed.

- - - /** - * A JSDoc comment should begin with a slash and 2 asterisks. - * Inline tags should be enclosed in braces like {@code this}. - * @desc Block tags should always start on their own line. - */ - -
- - -

If you have to line break a block tag, you should treat this as - breaking a code statement and indent it four spaces.

- - - /** - * Illustrates line wrapping for long param/return descriptions. - * @param {string} foo This is a param with a description too long to fit in - * one line. - * @return {number} This returns something that has a description too long to - * fit in one line. - */ - project.MyClass.prototype.method = function(foo) { - return 5; - }; - - -

You should not indent the @fileoverview command. You do not have to - indent the @desc command.

- -

Even though it is not preferred, it is also acceptable to line up - the description.

- - - /** - * This is NOT the preferred indentation method. - * @param {string} foo This is a param with a description too long to fit in - * one line. - * @return {number} This returns something that has a description too long to - * fit in one line. - */ - project.MyClass.prototype.method = function(foo) { - return 5; - }; - -
- - -

Like JavaDoc, JSDoc supports many HTML tags, like <code>, - <pre>, <tt>, <strong>, <ul>, <ol>, - <li>, <a>, and others.

- -

This means that plaintext formatting is not respected. So, don't - rely on whitespace to format JSDoc:

- - - /** - * Computes weight based on three factors: - * items sent - * items received - * last timestamp - */ - - -

It'll come out like this:

- - - Computes weight based on three factors: items sent items received last timestamp - - -

Instead, do this:

- - - /** - * Computes weight based on three factors: - * <ul> - * <li>items sent - * <li>items received - * <li>last timestamp - * </ul> - */ - - - The - JavaDoc style guide is a useful resource on how to write - well-formed doc comments. -
- - -

- - A copyright notice and author information are optional. - File overviews are generally recommended whenever a file consists of - more than a single class definition. The top level comment is - designed to orient readers unfamiliar with the code to what is in - this file. If present, it should provide a description of the - file's contents and any dependencies or compatibility information. - As an example: -

- - - /** - * @fileoverview Description of file, its uses and information - * about its dependencies. - */ - - - -
- - -

Classes must be documented with a description and a - type tag that - identifies the constructor. -

- - - /** - * Class making something fun and easy. - * @param {string} arg1 An argument that makes this more interesting. - * @param {Array.<number>} arg2 List of numbers to be processed. - * @constructor - * @extends {goog.Disposable} - */ - project.MyClass = function(arg1, arg2) { - // ... - }; - goog.inherits(project.MyClass, goog.Disposable); - -
- - -

Parameter and return types should be documented. The method - description may be omitted if it is obvious from the parameter - or return type descriptions. Method descriptions should start - with a sentence written in the third person declarative voice.

- - /** - * Operates on an instance of MyClass and returns something. - * @param {project.MyClass} obj Instance of MyClass which leads to a long - * comment that needs to be wrapped to two lines. - * @return {boolean} Whether something occurred. - */ - function PR_someMethod(obj) { - // ... - } - -
- - - - /** @constructor */ - project.MyClass = function() { - /** - * Maximum number of things per pane. - * @type {number} - */ - this.someProperty = 4; - } - - - - - -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TagTemplate & ExamplesDescription
- @author - - - @author username@google.com (first last) -

For example:

- - /** - * @fileoverview Utilities for handling textareas. - * @author kuth@google.com (Uthur Pendragon) - */ - -
- Document the author of a file or the owner of a test, - generally only used in the @fileoverview comment. - -
@code - {@code ...} -

For example:

- - /** - * Moves to the next position in the selection. - * Throws {@code goog.iter.StopIteration} when it - * passes the end of the range. - * @return {Node} The node at the next position. - */ - goog.dom.RangeIterator.prototype.next = function() { - // ... - }; - -
- Indicates that a term in a JSDoc description is code so it may - be correctly formatted in generated documentation. -
@const - @const
- @const {type} -

For example:

- - /** @const */ var MY_BEER = 'stout'; - - /** - * My namespace's favorite kind of beer. - * @const {string} - */ - mynamespace.MY_BEER = 'stout'; - - /** @const */ MyClass.MY_BEER = 'stout'; - - /** - * Initializes the request. - * @const - */ - mynamespace.Request.prototype.initialize = function() { - // This method cannot be overridden in a subclass. - }; - -
-

Marks a variable (or property) as read-only and suitable - for inlining.

- -

A @const variable is an immutable pointer to - a value. If a variable or property marked as - @const is overwritten, JSCompiler will give - warnings.

- -

The type declaration of a constant value can be omitted - if it can be clearly inferred. An additional comment about - the variable is optional.

- -

When @const is applied to a method, it - implies the method is not only not overwritable, but also - that the method is finalized — - not overridable in subclasses.

- -

For more on @const, see the - Constants section.

- -
@constructor - @constructor -

For example:

- - /** - * A rectangle. - * @constructor - */ - function GM_Rect() { - ... - } - -
- Used in a class's documentation to indicate the constructor. -
@define - @define {Type} description -

For example:

- - /** @define {boolean} */ - var TR_FLAGS_ENABLE_DEBUG = true; - - /** - * @define {boolean} Whether we know at compile-time that - * the browser is IE. - */ - goog.userAgent.ASSUME_IE = false; - -
- Indicates a constant that can be overridden by the compiler at - compile-time. In the example, the compiler flag - --define='goog.userAgent.ASSUME_IE=true' - could be specified in the BUILD file to indicate that the - constant goog.userAgent.ASSUME_IE should be replaced - with true. -
@deprecated - @deprecated Description -

For example:

- - /** - * Determines whether a node is a field. - * @return {boolean} True if the contents of - * the element are editable, but the element - * itself is not. - * @deprecated Use isField(). - */ - BN_EditUtil.isTopEditableField = function(node) { - // ... - }; - -
- Used to tell that a function, method or property should not be - used any more. Always provide instructions on what callers - should use instead. -
@dict - @dict Description -

For example:

- - /** - * @constructor - * @dict - */ - function Foo(x) { - this['x'] = x; - } - var obj = new Foo(123); - var num = obj.x; // warning - - (/** @dict */ { x: 1 }).x = 123; // warning - -
- When a constructor (Foo in the example) is - annotated with @dict, you can only use the - bracket notation to access the properties of Foo - objects. - The annotation can also be used directly on object literals. -
@enum - @enum {Type} -

For example:

- - /** - * Enum for tri-state values. - * @enum {number} - */ - project.TriState = { - TRUE: 1, - FALSE: -1, - MAYBE: 0 - }; - -
@export - @export -

For example:

- - /** @export */ - foo.MyPublicClass.prototype.myPublicMethod = function() { - // ... - }; - -
-

Given the code on the left, when the compiler is run with - the --generate_exports flag, it will generate the - code:

- - goog.exportSymbol('foo.MyPublicClass.prototype.myPublicMethod', - foo.MyPublicClass.prototype.myPublicMethod); - -

which will export the symbols to uncompiled code. - Code that uses the @export annotation must either

-
    -
  1. include //javascript/closure/base.js, or
  2. -
  3. define both goog.exportSymbol and - goog.exportProperty with the same method - signature in their own codebase.
  4. -
-
@expose - @expose -

For example:

- - /** @expose */ - MyClass.prototype.exposedProperty = 3; - -
-

- Declares an exposed property. Exposed properties - will not be removed, or renamed, or collapsed, - or optimized in any way by the compiler. No properties - with the same name will be able to be optimized either. -

- -

- @expose should never be used in library code, - because it will prevent that property from ever getting - removed. -

-
@extends - - @extends Type
- @extends {Type} -
-

For example:

- - /** - * Immutable empty node list. - * @constructor - * @extends goog.ds.BasicNodeList - */ - goog.ds.EmptyNodeList = function() { - ... - }; - -
- Used with @constructor to indicate that a class - inherits from another class. Curly braces around the type are - optional. -
@externs - @externs -

For example:

- - /** - * @fileoverview This is an externs file. - * @externs - */ - - var document; - -
-

- Declares an - - externs file. -

- - -
@fileoverview - @fileoverview Description -

For example:

- - /** - * @fileoverview Utilities for doing things that require this very long - * but not indented comment. - * @author kuth@google.com (Uthur Pendragon) - */ - -
Makes the comment block provide file level information.
@implements - - @implements Type
- @implements {Type} -
-

For example:

- - /** - * A shape. - * @interface - */ - function Shape() {}; - Shape.prototype.draw = function() {}; - - /** - * @constructor - * @implements {Shape} - */ - function Square() {}; - Square.prototype.draw = function() { - ... - }; - -
- Used with @constructor to indicate that a class - implements an interface. Curly braces around the type are - optional. -
@inheritDoc - @inheritDoc -

For example:

- - /** @inheritDoc */ - project.SubClass.prototype.toString() { - // ... - }; - -
-

Deprecated. Use - @override instead.

- - Indicates that a method or property of a subclass - intentionally hides a method or property of the superclass, - and has exactly the same documentation. Notice that - @inheritDoc implies @override -
@interface - @interface -

For example:

- - /** - * A shape. - * @interface - */ - function Shape() {}; - Shape.prototype.draw = function() {}; - - /** - * A polygon. - * @interface - * @extends {Shape} - */ - function Polygon() {}; - Polygon.prototype.getSides = function() {}; - -
- Used to indicate that the function defines an interface. -
@lends - @lends objectName
- @lends {objectName} -

For example:

- - goog.object.extend( - Button.prototype, - /** @lends {Button.prototype} */ { - isButton: function() { return true; } - }); - -
- Indicates that the keys of an object literal should - be treated as properties of some other object. This annotation - should only appear on object literals.

- - Notice that the name in braces is not a type name like - in other annotations. It's an object name. It names - the object on which the properties are "lent". - For example, @type {Foo} means "an instance of Foo", - but @lends {Foo} means "the constructor Foo".

- - The - JSDoc Toolkit docs have more information on this - annotation. -

@license or - @preserve - @license Description -

For example:

- - /** - * @preserve Copyright 2009 SomeThirdParty. - * Here is the full license text and copyright - * notice for this file. Note that the notice can span several - * lines and is only terminated by the closing star and slash: - */ - -
- Anything marked by @license or - @preserve will be retained by the compiler and - output at the top of the compiled code for that file. This - annotation allows important notices (such as legal licenses or - copyright text) to survive compilation unchanged. Line breaks - are preserved. -
@noalias - @noalias -

For example:

- - /** @noalias */ - function Range() {} - -
- Used in an externs file to indicate to the compiler that the - variable or function should not be aliased as part of the - alias externals pass of the compiler. -
@nocompile - @nocompile -

For example:

- - /** @nocompile */ - - // JavaScript code - -
- Used at the top of a file to tell the compiler to parse this - file but not compile it. - Code that is not meant for compilation and should be omitted - from compilation tests (such as bootstrap code) uses this - annotation. - Use sparingly. -
@nosideeffects - @nosideeffects -

For example:

- - /** @nosideeffects */ - function noSideEffectsFn1() { - // ... - } - - /** @nosideeffects */ - var noSideEffectsFn2 = function() { - // ... - }; - - /** @nosideeffects */ - a.prototype.noSideEffectsFn3 = function() { - // ... - }; - -
- This annotation can be used as part of function and - constructor declarations to indicate that calls to the - declared function have no side-effects. This annotation - allows the compiler to remove calls to these functions if the - return value is not used. -
@override - @override -

For example:

- - /** - * @return {string} Human-readable representation of project.SubClass. - * @override - */ - project.SubClass.prototype.toString = function() { - // ... - }; - -
- Indicates that a method or property of a subclass - intentionally hides a method or property of the superclass. If - no other documentation is included, the method or property - also inherits documentation from its superclass. -
@param - @param {Type} varname Description -

For example:

- - /** - * Queries a Baz for items. - * @param {number} groupNum Subgroup id to query. - * @param {string|number|null} term An itemName, - * or itemId, or null to search everything. - */ - goog.Baz.prototype.query = function(groupNum, term) { - // ... - }; - -
- Used with method, function and constructor calls to document - the arguments of a function.

- - Type - names must be enclosed in curly braces. If the type - is omitted, the compiler will not type-check the parameter. -

@private - @private
- @private {type} -

For example:

- - /** - * Handlers that are listening to this logger. - * @private {!Array.<Function>} - */ - this.handlers_ = []; - -
- Used in conjunction with a trailing underscore on the method - or property name to indicate that the member is - private and final. -
@protected - @protected
- @protected {type} -

For example:

- - /** - * Sets the component's root element to the given element. - * @param {Element} element Root element for the component. - * @protected - */ - goog.ui.Component.prototype.setElementInternal = function(element) { - // ... - }; - -
- Used to indicate that the member or property is - protected. - Should be used in conjunction with names with no trailing - underscore. -
@public - @public
- @public {type} -

For example:

- - /** - * Whether to cancel the event in internal capture/bubble processing. - * @public {boolean} - * @suppress {visiblity} Referencing this outside this package is strongly - * discouraged. - */ - goog.events.Event.prototype.propagationStopped_ = false; - -
- Used to indicate that the member or property is public. Variables and - properties are public by default, so this annotation is rarely necessary. - Should only be used in legacy code that cannot be easily changed to - override the visibility of members that were named as private variables. -
@return - @return {Type} Description -

For example:

- - /** - * @return {string} The hex ID of the last item. - */ - goog.Baz.prototype.getLastId = function() { - // ... - return id; - }; - -
- Used with method and function calls to document the return - type. When writing descriptions for boolean parameters, - prefer "Whether the component is visible" to "True if the - component is visible, false otherwise". If there is no return - value, do not use an @return tag.

- - Type - names must be enclosed in curly braces. If the type - is omitted, the compiler will not type-check the return value. -

@see - @see Link -

For example:

- - /** - * Adds a single item, recklessly. - * @see #addSafely - * @see goog.Collect - * @see goog.RecklessAdder#add - ... - -
Reference a lookup to another class function or method.
@struct - @struct Description -

For example:

- - /** - * @constructor - * @struct - */ - function Foo(x) { - this.x = x; - } - var obj = new Foo(123); - var num = obj['x']; // warning - obj.y = "asdf"; // warning - - Foo.prototype = /** @struct */ { - method1: function() {} - }; - Foo.prototype.method2 = function() {}; // warning - -
- When a constructor (Foo in the example) is - annotated with @struct, you can only use the dot - notation to access the properties of Foo objects. - Also, you cannot add new properties to Foo - objects after they have been created. - The annotation can also be used directly on object literals. -
@supported - @supported Description -

For example:

- - /** - * @fileoverview Event Manager - * Provides an abstracted interface to the - * browsers' event systems. - * @supported So far tested in IE6 and FF1.5 - */ - -
- Used in a fileoverview to indicate what browsers are supported - by the file. -
@suppress - - @suppress {warning1|warning2} - - - @suppress {warning1,warning2} - -

For example:

- - /** - * @suppress {deprecated} - */ - function f() { - deprecatedVersionOfF(); - } - -
- Suppresses warnings from tools. Warning categories are - separated by | or ,. - -
@template - @template -

For example:

- - /** - * @param {function(this:T, ...)} fn - * @param {T} thisObj - * @param {...*} var_args - * @template T - */ - goog.bind = function(fn, thisObj, var_args) { - ... - }; - -
- This annotation can be used to declare a - template typename. -
@this - - @this Type
- @this {Type} -
-

For example:

- - pinto.chat.RosterWidget.extern('getRosterElement', - /** - * Returns the roster widget element. - * @this pinto.chat.RosterWidget - * @return {Element} - */ - function() { - return this.getWrappedComponent_().getElement(); - }); - -
- The type of the object in whose context a particular method is - called. Required when the this keyword is referenced - from a function that is not a prototype method. -
@type - - @type Type
- @type {Type} -
-

For example:

- - /** - * The message hex ID. - * @type {string} - */ - var hexId = hexId; - -
- Identifies the type of a variable, - property, or expression. Curly braces are not required around - most types, but some projects mandate them for all types, for - consistency. -
@typedef - @typedef -

For example:

- - /** @typedef {(string|number)} */ - goog.NumberLike; - - /** @param {goog.NumberLike} x A number or a string. */ - goog.readNumber = function(x) { - ... - } - -
- This annotation can be used to declare an alias of a more - complex type. -
- - - -

- You may also see other types of JSDoc annotations in third-party - code. These annotations appear in the - - JSDoc Toolkit Tag Reference - - but are currently discouraged in Google code. You should consider - them "reserved" names for future use. These include: -

    -
  • @augments
  • -
  • @argument
  • -
  • @borrows
  • -
  • @class
  • -
  • @constant
  • -
  • @constructs
  • -
  • @default
  • -
  • @event
  • -
  • @example
  • -
  • @field
  • -
  • @function
  • -
  • @ignore
  • -
  • @inner
  • -
  • @link
  • -
  • @memberOf
  • -
  • @name
  • -
  • @namespace
  • -
  • @property
  • -
  • @public
  • -
  • @requires
  • -
  • @returns
  • -
  • @since
  • -
  • @static
  • -
  • @version
  • -
-

-
- - - - - - Only provide top-level symbols. - - -

- All members defined on a class should be in the same file. So, only - top-level classes should be provided in a file that contains multiple - members defined on the same class (e.g. enums, inner classes, etc). -

-

Do this:

- - goog.provide('namespace.MyClass'); - -

Not this:

- - goog.provide('namespace.MyClass'); - goog.provide('namespace.MyClass.Enum'); - goog.provide('namespace.MyClass.InnerClass'); - goog.provide('namespace.MyClass.TypeDef'); - goog.provide('namespace.MyClass.CONSTANT'); - goog.provide('namespace.MyClass.staticMethod'); - -

- Members on namespaces may also be provided: -

- - goog.provide('foo.bar'); - goog.provide('foo.bar.method'); - goog.provide('foo.bar.CONSTANT'); - - -
- - - Required - - - -

Use of JS compilers such as the - Closure Compiler - is required for all customer-facing code.

- - - - - -
- - - JavaScript tidbits - - -

The following are all false in boolean expressions:

-
    -
  • null
  • -
  • undefined
  • -
  • '' the empty string
  • -
  • 0 the number
  • -
-

But be careful, because these are all true:

-
    -
  • '0' the string
  • -
  • [] the empty array
  • -
  • {} the empty object
  • -
- -

This means that instead of this:

- - while (x != null) { - -

you can write this shorter code (as long as you don't expect x to - be 0, or the empty string, or false):

- - while (x) { - - -

And if you want to check a string to see if it is null or empty, - you could do this:

- - if (y != null && y != '') { - -

But this is shorter and nicer:

- - if (y) { - - -

Caution: There are many unintuitive things about - boolean expressions. Here are some of them:

-
    -
  • - Boolean('0') == true
    - '0' != true
  • -
  • - 0 != null
    - 0 == []
    - 0 == false
  • -
  • - Boolean(null) == false
    - null != true
    - null != false
  • -
  • - Boolean(undefined) == false
    - undefined != true
    - undefined != false
  • -
  • - Boolean([]) == true
    - [] != true
    - [] == false
  • -
  • - Boolean({}) == true
    - {} != true
    - {} != false
  • -
-
- - -

Instead of this:

- - if (val) { - return foo(); - } else { - return bar(); - } - -

you can write this:

- - return val ? foo() : bar(); - - -

The ternary conditional is also useful when generating HTML:

- - var html = '<input type="checkbox"' + - (isChecked ? ' checked' : '') + - (isEnabled ? '' : ' disabled') + - ' name="foo">'; - -
- - -

These binary boolean operators are short-circuited, and evaluate - to the last evaluated term.

- -

"||" has been called the 'default' operator, because instead of - writing this:

- - /** @param {*=} opt_win */ - function foo(opt_win) { - var win; - if (opt_win) { - win = opt_win; - } else { - win = window; - } - // ... - } - -

you can write this:

- - /** @param {*=} opt_win */ - function foo(opt_win) { - var win = opt_win || window; - // ... - } - - -

"&&" is also useful for shortening code. For instance, - instead of this:

- - if (node) { - if (node.kids) { - if (node.kids[index]) { - foo(node.kids[index]); - } - } - } - - -

you could do this:

- - if (node && node.kids && node.kids[index]) { - foo(node.kids[index]); - } - - -

or this:

- - var kid = node && node.kids && node.kids[index]; - if (kid) { - foo(kid); - } - - -

However, this is going a little too far:

- - node && node.kids && node.kids[index] && foo(node.kids[index]); - -
- - -

Node lists are often implemented as node iterators with a filter. - This means that getting a property like length is O(n), and - iterating over the list by re-checking the length will be - O(n^2).

- - var paragraphs = document.getElementsByTagName('p'); - for (var i = 0; i < paragraphs.length; i++) { - doSomething(paragraphs[i]); - } - - -

It is better to do this instead:

- - var paragraphs = document.getElementsByTagName('p'); - for (var i = 0, paragraph; paragraph = paragraphs[i]; i++) { - doSomething(paragraph); - } - - -

This works well for all collections and arrays as long as the array - does not contain things that are treated as boolean false.

- -

In cases where you are iterating over the childNodes you can also - use the firstChild and nextSibling properties.

- - var parentNode = document.getElementById('foo'); - for (var child = parentNode.firstChild; child; child = child.nextSibling) { - doSomething(child); - } - -
- -
-
- - - - -

- BE CONSISTENT. -

- -

- If you're editing code, take a few minutes to look at the code - around you and determine its style. If they use spaces around - all their arithmetic operators, you should too. If their - comments have little boxes of hash marks around them, make your - comments have little boxes of hash marks around them too. -

- -

- The point of having style guidelines is to have a common vocabulary - of coding so people can concentrate on what you're saying rather - than on how you're saying it. We present global style rules here so - people know the vocabulary, but local style is also important. If - code you add to a file looks drastically different from the existing - code around it, it throws readers out of their rhythm when they go to - read it. Avoid this. -

- -
- -

- Revision 2.93 -

- - -
- Aaron Whyte
- Bob Jervis
- Dan Pupius
- Erik Arvidsson
- Fritz Schneider
- Robby Walker
-
diff --git a/jsguide.html b/jsguide.html new file mode 100644 index 000000000..25cfe4893 --- /dev/null +++ b/jsguide.html @@ -0,0 +1,2650 @@ + + + + +Google JavaScript Style Guide + + + + + + +
+

Google JavaScript Style Guide

+

1 Introduction

+ +

+ +

This document serves as the complete definition of Google’s coding standards +for source code in the JavaScript programming language. A JavaScript source file +is described as being in Google Style if and only if it adheres to the rules +herein.

+ +

Like other programming style guides, the issues covered span not only aesthetic +issues of formatting, but other types of conventions or coding standards as +well. However, this document focuses primarily on the hard-and-fast rules that +we follow universally, and avoids giving advice that isn't clearly enforceable +(whether by human or tool).

+ +

1.1 Terminology notes

+ +

In this document, unless otherwise clarified:

+ +
    +
  1. The term comment always refers to implementation comments. We do not use +the phrase documentation comments, instead using the common term “JSDoc” +for both human-readable text and machine-readable annotations within +/** … */.

  2. +
  3. This Style Guide uses RFC 2119 terminology when using the phrases must, +must not, should, should not, and may. The terms prefer and +avoid correspond to should and should not, respectively. Imperative +and declarative statements are prescriptive and correspond to must.

  4. +
+ +

Other terminology notes will appear occasionally throughout the document.

+ +

1.2 Guide notes

+ +

Example code in this document is non-normative. That is, while the examples +are in Google Style, they may not illustrate the only stylish way to represent +the code. Optional formatting choices made in examples must not be enforced as +rules.

+ +

2 Source file basics

+ +

2.1 File name

+ +

File names must be all lowercase and may include underscores (_) or dashes +(-), but no additional punctuation. Follow the convention that your project +uses. Filenames’ extension must be .js.

+ +

2.2 File encoding: UTF-8

+ +

Source files are encoded in UTF-8.

+ +

2.3 Special characters

+ +

2.3.1 Whitespace characters

+ +

Aside from the line terminator sequence, the ASCII horizontal space character +(0x20) is the only whitespace character that appears anywhere in a source +file. This implies that

+ +
    +
  1. All other whitespace characters in string literals are escaped, and

  2. +
  3. Tab characters are not used for indentation.

  4. +
+ +

2.3.2 Special escape sequences

+ +

For any character that has a special escape sequence (\', \", \\, \b, +\f, \n, \r, \t, \v), that sequence is used rather than the +corresponding numeric escape (e.g \x0a, \u000a, or \u{a}). Legacy octal +escapes are never used.

+ +

2.3.3 Non-ASCII characters

+ +

For the remaining non-ASCII characters, either the actual Unicode character +(e.g. ) or the equivalent hex or Unicode escape (e.g. \u221e) is used, +depending only on which makes the code easier to read and understand.

+ +

Tip: In the Unicode escape case, and occasionally even when actual Unicode +characters are used, an explanatory comment can be very helpful.

+ + + + + + + + + + +
Example + Discussion +
const units = 'μs'; + Best: perfectly clear even without a comment. +
+ const units = '\u03bcs'; // 'μs' + + Allowed, but there’s no reason to do this. +
+ const units = '\u03bcs'; // Greek letter mu, 's' + + Allowed, but awkward and prone to mistakes. +
const units = '\u03bcs'; + Poor: the reader has no idea what this is. +
+ return '\ufeff' + content; // byte order mark + + + Good: use escapes for non-printable characters, and comment if + necessary. +
+ +

Tip: Never make your code less readable simply out of fear that some programs +might not handle non-ASCII characters properly. If that happens, those programs +are broken and they must be fixed.

+ +

3 Source file structure

+ +

A source file consists of, in order:

+ +
    +
  1. License or copyright information, if present
  2. +
  3. @fileoverview JSDoc, if present
  4. +
  5. goog.module statement
  6. +
  7. goog.require statements
  8. +
  9. The file’s implementation
  10. +
+ +

Exactly one blank line separates each section that is present, except the +file's implementation, which may be preceded by 1 or 2 blank lines.

+ + + +

If license or copyright information belongs in a file, it belongs here.

+ +

+ +

+ +

3.2 @fileoverview JSDoc, if present

+ +

See ?? for formatting rules.

+ +

3.3 goog.module statement

+ +

All files must declare exactly one goog.module name on a single line: lines +containing a goog.module declaration must not be wrapped, and are therefore an +exception to the 80-column limit.

+ +

The single goog.module statement may optionally be followed by calls to +goog.module.declareLegacyNamespace(); and/or goog.setTestOnly(); Avoid +goog.module.declareLegacyNamespace() when possible.

+ +

Example:

+ +
goog.module('my.test.helpers');
+goog.module.declareLegacyNamespace();
+goog.setTestOnly();
+
+ +

3.3.1 goog.module.declareLegacyNamespace

+ +

goog.module.declareLegacyNamespace exists to ease the transition from +traditional namespaces but comes with some naming restrictions. As the child +module name must be created after the parent namespace, this name must not +be a child or parent of any other goog.module (for example, +goog.module('parent'); and goog.module('parent.child'); cannot both exist, +nor can goog.module('parent'); and goog.module('parent.child.grandchild');).

+ +

3.3.2 ES6 Modules

+ +

Do not use ES6 modules yet (i.e. the export and import keywords), as their +semantics are not yet finalized. Note that this policy will be revisited once +the semantics are fully-standard.

+ +

3.4 goog.require statements

+ +

Imports are done with goog.require statements, grouped together immediately +following the module declaration. Each goog.require is assigned to a single +constant alias, or else destructured into several constant aliases. These +aliases are the only acceptable way to refer to the required dependency, +whether in code or in type annotations: the fully qualified name is never used +except as the argument to goog.require. If a module is imported only for its +side effects, the assignment may be omitted, but the fully qualified name may +not appear anywhere else in the file. Alias names should match the final +dot-separated component of the imported module name when possible, though +additional components may be included (with appropriate casing such that the +alias' casing still correctly identifies its type) if necessary to +disambiguate, or if it significantly improves readability. goog.require +statements may not appear anywhere else in the file.

+ + + +

The lines are sorted via standard ASCII ordering of the entire line, with +uppercase letters, then lowercase letters, then open-braces (for +destructuring). Aliases within a destructured expression are sorted the same +way.

+ +

Tip: There’s no need to memorize this order and enforce it manually. You can +rely on your IDE or even sort to sort your imports automatically.

+ +

If a long alias or module name would cause a line to exceed the 80-column limit, +it must not be wrapped: goog.require lines are an exception to the 80-column +limit.

+ +

Example:

+ +
const MyClass = goog.require('some.package.MyClass');
+const NsMyClass = goog.require('other.ns.MyClass');
+const googAsserts = goog.require('goog.asserts');
+const testingAsserts = goog.require('goog.testing.asserts');
+const than80columns = goog.require('pretend.this.is.longer.than80columns');
+const {clear, forEach, map} = goog.require('goog.array');
+
+ +

Illegal:

+ +
const randomName = goog.require('something.else'); // name must match
+
+const {clear, forEach, map} = // don't break lines
+    goog.require('goog.array');
+
+function someFunction() {
+  const alias = goog.require('my.long.name.alias'); // must be at top level
+  // …
+}
+
+ + + +

3.5 The file’s implementation

+ +

The actual implementation follows after all dependency information is declared +(separated by at least one blank line).

+ +

This may consist of any module-local declarations (constants, variables, +classes, functions, etc), as well as any exported symbols. +

+ +

4 Formatting

+ +

Terminology Note: block-like construct refers to the body of a class, +function, method, or brace-delimited block of code. Note that, by +?? and ??, any array or +object literal may optionally be treated as if it were a block-like construct.

+ +

Tip: Use clang-format. The JavaScript community has invested effort to make +sure clang-format does the right thing on JavaScript files.

+ +

4.1 Braces

+ +

4.1.1 Braces are used for all control structures

+ +

Braces are required for all control structures (i.e. if, else, for, do, +while, as well as any others), even if the body contains only a single +statement. The first statement of a non-empty block must begin on its own line.

+ +

Illegal:

+ +
if (someVeryLongCondition())
+  doSomething();
+
+for (let i = 0; i < foo.length; i++) bar(foo[i]);
+
+ +

Exception: A simple if statement that can fit entirely on a single line with +no wrapping (and that doesn’t have an else) may be kept on a single line with no +braces when it improves readability. This is the only case in which a control +structure may omit braces and newlines.

+ +
if (shortCondition()) return;
+
+ +

4.1.2 Nonempty blocks: K&R style

+ +

Braces follow the Kernighan and Ritchie style (Egyptian brackets) for +nonempty blocks and block-like constructs:

+ + + +

Example:

+ +
class InnerClass {
+  constructor() {}
+
+  /** @param {number} foo */
+  method(foo) {
+    if (condition(foo)) {
+      try {
+        // Note: this might fail.
+        something();
+      } catch (err) {
+        recover();
+      }
+    }
+  }
+}
+
+ +

4.1.3 Empty blocks: may be concise

+ +

An empty block or block-like construct may be closed immediately after it is +opened, with no characters, space, or line break in between (i.e. {}), +unless it is a part of a multi-block statement (one that directly contains +multiple blocks: if/else or try/catch/finally).

+ +

Example:

+ +
function doNothing() {}
+
+ +

Illegal:

+ +
if (condition) {
+  // …
+} else if (otherCondition) {} else {
+  // …
+}
+
+try {
+  // …
+} catch (e) {}
+
+ +

4.2 Block indentation: +2 spaces

+ +

Each time a new block or block-like construct is opened, the indent increases by +two spaces. When the block ends, the indent returns to the previous indent +level. The indent level applies to both code and comments throughout the +block. (See the example in ??).

+ +

4.2.1 Array literals: optionally block-like

+ +

Any array literal may optionally be formatted as if it were a “block-like +construct.” For example, the following are all valid (not an exhaustive +list):

+ +
const a = [
+  0, 1, 2,
+];
+
+const b =
+    [0, 1, 2];
+
+
+ +
const c = [0, 1, 2];
+
+someMethod(foo, [
+  0,
+  1,
+  2,
+], bar);
+
+ +

Other combinations are allowed, particularly when emphasizing semantic groupings +between elements, but should not be used only to reduce the vertical size of +larger arrays.

+ +

4.2.2 Object literals: optionally block-like

+ +

Any object literal may optionally be formatted as if it were a “block-like +construct.” The same examples apply as ??. For +example, the following are all valid (not an exhaustive list):

+ +
const a = {
+  a: 0, b: 1
+};
+
+const b =
+    {a: 0, b: 1};
+
+ +
const c = {a: 0, b: 1};
+
+someMethod(foo, {
+  a: 0,
+  b: 1,
+}, bar);
+
+ +

4.2.3 Class literals

+ +

Class literals (whether declarations or expressions) are indented as blocks. Do +not add commas after methods, or a semicolon after the closing brace of a class +declaration (statements—such as assignments—that contain class expressions +are still terminated with a semicolon).

+ +

Example:

+ +
class Foo {
+  constructor() {
+    /** @type {number} */
+    this.x = 42;
+  }
+
+  /** @return {number} */
+  method() {
+    return this.x;
+  }
+}
+Foo.Empty = class {};
+
+ +
foo.Bar = class extends Foo {
+  /** @override */
+  method() {
+    return super.method() / 2;
+  }
+};
+
+/** @interface */
+class Frobnicator {
+  /** @param {string} message */
+  frobnicate(message) {}
+}
+
+ +

4.2.4 Function expressions

+ +

When declaring an anonymous function in the list of arguments for a function +call, the body of the function is indented two spaces more than the preceding +indentation depth.

+ +

Example:

+ +
prefix.something.reallyLongFunctionName('whatever', (a1, a2) => {
+  // Indent the function body +2 relative to indentation depth
+  // of the 'prefix' statement one line above.
+  if (a1.equals(a2)) {
+    someOtherLongFunctionName(a1);
+  } else {
+    andNowForSomethingCompletelyDifferent(a2.parrot);
+  }
+});
+
+some.reallyLongFunctionCall(arg1, arg2, arg3)
+    .thatsWrapped()
+    .then((result) => {
+      // Indent the function body +2 relative to the indentation depth
+      // of the '.then()' call.
+      if (result) {
+        result.use();
+      }
+    });
+
+ +

4.2.5 Switch statements

+ +

As with any other block, the contents of a switch block are indented +2.

+ + + +

After a switch label, a newline appears, and the indentation level is increased ++2, exactly as if a block were being opened. An explicit block may be used if +required by lexical scoping. The following switch label returns to the previous +indentation level, as if a block had been closed.

+ +

A blank line is optional between a break and the following case.

+ +

Example:

+ +
switch (animal) {
+  case Animal.BANDERSNATCH:
+    handleBandersnatch();
+    break;
+
+  case Animal.JABBERWOCK:
+    handleJabberwock();
+    break;
+
+  default:
+    throw new Error('Unknown animal');
+}
+
+ +

4.3 Statements

+ +

4.3.1 One statement per line

+ +

Each statement is followed by a line-break.

+ +

4.3.2 Semicolons are required

+ +

Every statement must be terminated with a semicolon. Relying on automatic +semicolon insertion is forbidden.

+ +

4.4 Column limit: 80

+ +

JavaScript code has a column limit of 80 characters. Except as noted below, any +line that would exceed this limit must be line-wrapped, as explained in +??.

+ +

Exceptions:

+ +
    +
  1. Lines where obeying the column limit is not possible (for example, a long URL +in JSDoc or a shell command intended to be copied-and-pasted).
  2. +
  3. goog.module and goog.require statements (see ?? and +??).
  4. +
+ +

4.5 Line-wrapping

+ +

Terminology Note: Line-wrapping is defined as breaking a single expression +into multiple lines.

+ +

There is no comprehensive, deterministic formula showing exactly how to +line-wrap in every situation. Very often there are several valid ways to +line-wrap the same piece of code.

+ +

Note: While the typical reason for line-wrapping is to avoid overflowing the +column limit, even code that would in fact fit within the column limit may be +line-wrapped at the author's discretion.

+ +

Tip: Extracting a method or local variable may solve the problem without the +need to line-wrap.

+ +

4.5.1 Where to break

+ +

The prime directive of line-wrapping is: prefer to break at a higher syntactic +level. Also:

+ +
    +
  1. When a line is broken at an operator the break comes after the symbol. (Note +that this is not the same practice used in Google style for Java.) +
      +
    1. This does not apply to the dot (.), which is not actually an +operator.
    2. +
  2. +
  3. A method or constructor name stays attached to the open parenthesis (() +that follows it.
  4. +
  5. A comma (,) stays attached to the token that precedes it.
  6. +
+ +

Preferred:

+ +
this.foo =
+    foo(
+        firstArg,
+        1 + someLongFunctionName());
+
+ +

Discouraged:

+ +
this.foo = foo(firstArg, 1 +
+    someLongFunctionName());
+
+ +

In the preceding example, the syntactic levels from highest to lowest are as +follows: assignment, outer function call, parameters, plus, inner function call.

+ +

Note: The primary goal for line wrapping is to have clear code, not necessarily +code that fits in the smallest number of lines.

+ +

See also ??.

+ +

4.5.2 Indent continuation lines at least +4 spaces

+ +

When line-wrapping, each line after the first (each continuation line) is +indented at least +4 from the original line, unless it falls under the rules of +block indentation.

+ +

When there are multiple continuation lines, indentation may be varied beyond +4 +as appropriate. In general, continuation lines at a deeper syntactic level are +indented by larger multiples of 4, and two lines use the same indentation level +if and only if they begin with syntactically parallel elements.

+ +

?? addresses the discouraged practice of +using a variable number of spaces to align certain tokens with previous lines.

+ +

4.6 Whitespace

+ +

4.6.1 Vertical whitespace

+ +

A single blank line appears:

+ +
    +
  1. Between consecutive methods in a class or object literal +
      +
    1. Exception: A blank line between two consecutive properties definitions in +an object literal (with no other code between them) is optional. Such +blank lines are used as needed to create logical groupings of fields.
    2. +
  2. +
  3. Within method bodies, sparingly to create logical groupings of statements. +Blank lines at the start or end of a function body are not allowed.
  4. +
  5. Optionally before the first or after the last method in a class or object +literal (neither encouraged nor discouraged).
  6. +
  7. As required by other sections of this document (e.g. +??).
  8. +
+ +

Multiple consecutive blank lines are permitted, but never required (nor +encouraged).

+ +

4.6.2 Horizontal whitespace

+ +

Use of horizontal whitespace depends on location, and falls into three broad +categories: leading (at the start of a line), trailing (at the end of a +line), and internal. Leading whitespace (i.e., indentation) is addressed +elsewhere. Trailing whitespace is forbidden.

+ +

Beyond where required by the language or other style rules, and apart from +literals, comments, and JSDoc, a single internal ASCII space also appears in the +following places only.

+ +
    +
  1. Separating any reserved word (such as if, for, or catch) from an open +parenthesis (() that follows it on that line.
  2. +
  3. Separating any reserved word (such as else or catch) from a closing +curly brace (}) that precedes it on that line.
  4. +
  5. Before any open curly brace ({), with two exceptions: +
      +
    1. Before an object literal that is the first argument of a function or the +first element in an array literal (e.g. foo({a: [{c: d}]})).
    2. +
    3. In a template expansion, as it is forbidden by the language +(e.g. abc${1 + 2}def).
    4. +
  6. +
  7. On both sides of any binary or ternary operator.
  8. +
  9. After a comma (,) or semicolon (;). Note that spaces are never allowed +before these characters.
  10. +
  11. After the colon (:) in an object literal.
  12. +
  13. On both sides of the double slash (//) that begins an end-of-line +comment. Here, multiple spaces are allowed, but not required.
  14. +
  15. After an open-JSDoc comment character and on both sides of close characters +(e.g. for short-form type declarations or casts: this.foo = /** @type +{number} */ (bar); or function(/** string */ foo) {).
  16. +
+ +

4.6.3 Rectangle Rule

+ +

All code should follow the Rectangle Rule.

+ +

+When a source file is formatted, each subtree gets its own bounding rectangle, + containing all of that subtree’s text and none of any other subtree’s. +

+ +

+What does this mean? Take the well formatted example below, and draw a rectangle +around just the subexpression x / currentEstimate: +

+ +
   currentEstimate =
+        (currentEstimate + x / currentEstimate)
+            / 2.0f;
+
+ +

+This is possible—good! But in the badly formatted example, there is no rectangle +containing just that subexpression and nothing more—bad! +

+ +
   currentEstimate = (currentEstimate + x
+        / currentEstimate) / 2.0f;
+
+ +

+In the well formatted example, every subtree has its own rectangle; for +instance, the right-hand side (RHS) of the assignment has its own rectangle in +the well formatted example, but not in the other. This promotes readability by +exposing program structure in the physical layout; the RHS is in just one place, +not partly in one place and partly another. +

+ +

4.6.4 Horizontal alignment: discouraged

+ +

Terminology Note: Horizontal alignment is the practice of adding a +variable number of additional spaces in your code with the goal of making +certain tokens appear directly below certain other tokens on previous lines.

+ +

This practice is permitted, but it is generally discouraged by Google +Style. It is not even required to maintain horizontal alignment in places +where it was already used.

+ +

Here is an example without alignment, followed by one with alignment. Both are +allowed, but the latter is discouraged:

+ +
{
+  tiny: 42, // this is great
+  longer: 435, // this too
+};
+
+{
+  tiny:   42,  // permitted, but future edits
+  longer: 435, // may leave it unaligned
+};
+
+ +

Tip: Alignment can aid readability, but it creates problems for future +maintenance. Consider a future change that needs to touch just one line. This +change may leave the formerly-pleasing formatting mangled, and that is +allowed. More often it prompts the coder (perhaps you) to adjust whitespace on +nearby lines as well, possibly triggering a cascading series of +reformattings. That one-line change now has a blast radius. This can at worst +result in pointless busywork, but at best it still corrupts version history +information, slows down reviewers and exacerbates merge conflicts.

+ +

4.6.5 Function arguments

+ +

Prefer to put all function arguments on the same line as the function name. If doing so would exceed the 80-column limit, the arguments must be line-wrapped in a readable way. To save space, you may wrap as close to 80 as possible, or put each argument on its own line to enhance readability. Indentation should be four spaces. Aligning to the parenthesis is allowed, but discouraged. Below are the most common patterns for argument wrapping:

+ +
// Arguments start on a new line, indented four spaces. Preferred when the
+// arguments don't fit on the same line with the function name (or the keyword
+// "function") but fit entirely on the second line. Works with very long
+// function names, survives renaming without reindenting, low on space.
+doSomething(
+    descriptiveArgumentOne, descriptiveArgumentTwo, descriptiveArgumentThree) {
+  // …
+}
+
+// If the argument list is longer, wrap at 80. Uses less vertical space,
+// but violates the rectangle rule and is thus not recommended.
+doSomething(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,
+    tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {
+  // …
+}
+
+// Four-space, one argument per line.  Works with long function names,
+// survives renaming, and emphasizes each argument.
+doSomething(
+    veryDescriptiveArgumentNumberOne,
+    veryDescriptiveArgumentTwo,
+    tableModelEventHandlerProxy,
+    artichokeDescriptorAdapterIterator) {
+  // …
+}
+
+ +

4.7 Grouping parentheses: recommended

+ +

Optional grouping parentheses are omitted only when the author and reviewer +agree that there is no reasonable chance that the code will be misinterpreted +without them, nor would they have made the code easier to read. It is not +reasonable to assume that every reader has the entire operator precedence table +memorized.

+ +

Do not use unnecessary parentheses around the entire expression following +delete, typeof, void, return, throw, case, in, or of.

+ +

Parentheses are required for type casts: /** @type {!Foo} */ (foo).

+ +

4.8 Comments

+ +

This section addresses implementation comments. JSDoc is addressed separately +in ??.

+ +

4.8.1 Block comment style

+ +

Block comments are indented at the same level as the surrounding code. They may +be in /* … */ or //-style. For multi-line /* … */ comments, subsequent +lines must start with * aligned with the * on the previous line, to make +comments obvious with no extra context. “Parameter name” comments should appear +after values whenever the value and method name do not sufficiently convey the +meaning.

+ +
/*
+ * This is
+ * okay.
+ */
+
+// And so
+// is this.
+
+/* This is fine, too. */
+
+someFunction(obviousParam, true /* shouldRender */, 'hello' /* name */);
+
+ +

Comments are not enclosed in boxes drawn with asterisks or other characters.

+ +

Do not use JSDoc (/** … */) for any of the above implementation comments.

+ + + +

+ +
TODO(username): comment
+TODO(b/buganizer_id): comment
+
+ +

+ +
TODO(tashana): Remove this code after the UrlTable2 has been checked in.
+TODO(b/6002235): remove the "Last visitors" feature
+
+ +

+ +

+ +

5 Language features

+ +

JavaScript includes many dubious (and even dangerous) features. This section +delineates which features may or may not be used, and any additional constraints +on their use.

+ +

5.1 Local variable declarations

+ +

5.1.1 Use const and let

+ +

Declare all local variables with either const or let. Use const by default, +unless a variable needs to be reassigned. The var +keyword must not be used.

+ +

5.1.2 One variable per declaration

+ +

Every local variable declaration declares only one variable: declarations such +as let a = 1, b = 2; are not used.

+ +

5.1.3 Declared when needed, initialized as soon as possible

+ +

Local variables are not habitually declared at the start of their containing +block or block-like construct. Instead, local variables are declared close to +the point they are first used (within reason), to minimize their scope.

+ +

5.1.4 Declare types as needed

+ +

JSDoc type annotations may be added either on the line above the declaration, or +else inline before the variable name.

+ +

Example:

+ +
const /** !Array<number> */ data = [];
+
+/** @type {!Array<number>} */
+const data = [];
+
+ +

Tip: There are many cases where the compiler can infer a templatized type but +not its parameters. This is particularly the case when the initializing literal +or constructor call does not include any values of the template parameter type +(e.g., empty arrays, objects, Maps, or Sets), or if the variable is modified +in a closure. Local variable type annotations are particularly helpful in these +cases since otherwise the compiler will infer the template parameter as unknown.

+ +

5.2 Array literals

+ +

5.2.1 Use trailing commas

+ + + +

Include a trailing comma whenever there is a line break between the final +element and the closing bracket.

+ +

Example:

+ +
const values = [
+  'first value',
+  'second value',
+];
+
+ +

5.2.2 Do not use the variadic Array constructor

+ +

The constructor is error-prone if arguments are added or removed. Use a literal +instead.

+ +

Illegal:

+ +
const a1 = new Array(x1, x2, x3);
+const a2 = new Array(x1, x2);
+const a3 = new Array(x1);
+const a4 = new Array();
+
+ +

This works as expected except for the third case: if x1 is a whole number then +a3 is an array of size x1 where all elements are undefined. If x1 is any +other number, then an exception will be thrown, and if it is anything else then +it will be a single-element array.

+ +

Instead, write

+ +
const a1 = [x1, x2, x3];
+const a2 = [x1, x2];
+const a3 = [x1];
+const a4 = [];
+
+ +

Explicitly allocating an array of a given length using new Array(length) is +allowed when appropriate.

+ +

5.2.3 Non-numeric properties

+ +

Do not define or use non-numeric properties on an array (other than +length). Use a Map (or Object) instead.

+ +

5.2.4 Destructuring

+ +

Array literals may be used on the left-hand side of an assignment to perform +destructuring (such as when unpacking multiple values from a single array or +iterable. A final rest element may be included (with no space between the +... and the variable name). Elements should be omitted if they are unused.

+ +
const [a, b, c, ...rest] = generateResults();
+let [, b,, d] = someArray;
+
+ +

Destructuring may also be used for function parameters (note that a parameter +name is required but ignored). Always specify [] as the default value if a +destructured array parameter is optional, and provide default values on the left +hand side:

+ +
/** @param {!Array<number>=} param1 */
+function optionalDestructuring([a = 4, b = 2] = []) { … };
+
+ +

Illegal:

+ +
function badDestructuring([a, b] = [4, 2]) { … };
+
+ +

Tip: For (un)packing multiple values into a function’s parameter or return, +prefer object destructuring to array destructuring when possible, as it allows +naming the individual elements and specifying a different type for each.*

+ +

5.2.5 Spread operator

+ +

Array literals may include the spread operator (...) to flatten elements out +of one or more other iterables. The spread operator should be used instead of +more awkward constructs with Array.prototype. There is no space after the +....

+ +

Example:

+ +
[...foo]   // preferred over Array.prototype.slice.call(foo)
+[...foo, ...bar]   // preferred over foo.concat(bar)
+
+ +

5.3 Object literals

+ +

5.3.1 Use trailing commas

+ +

Include a trailing comma whenever there is a line break between the final +property and the closing brace.

+ +

5.3.2 Do not use the Object constructor

+ +

While Object does not have the same problems as Array, it is still +disallowed for consistency. Use an object literal ({} or {a: 0, b: 1, c: 2}) +instead.

+ +

5.3.3 Do not mix quoted and unquoted keys

+ +

Object literals may represent either structs (with unquoted keys and/or +symbols) or dicts (with quoted and/or computed keys). Do not mix these key +types in a single object literal.

+ +

Illegal:

+ +
{
+  a: 42, // struct-style unquoted key
+  'b': 43, // dict-style quoted key
+}
+
+ +

5.3.4 Computed property names

+ +

Computed property names (e.g., {['key' + foo()]: 42}) are allowed, and are +considered dict-style (quoted) keys (i.e., must not be mixed with non-quoted +keys) unless the computed property is a symbol (e.g., [Symbol.iterator]). +Enum values may also be used for computed keys, but should not be mixed with +non-enum keys in the same literal.

+ +

5.3.5 Method shorthand

+ +

Methods can be defined on object literals using the method shorthand ({method() +{… }}) in place of a colon immediately followed by a function or arrow +function literal.

+ +

Example:

+ +
return {
+  stuff: 'candy',
+  method() {
+    return this.stuff;  // Returns 'candy'
+  },
+};
+
+ +

Note that this in a method shorthand or function refers to the object +literal itself whereas this in an arrow function refers to the scope outside +the object literal.

+ +

Example:

+ +
class {
+  getObjectLiteral() {
+    this.stuff = 'fruit';
+    return {
+      stuff: 'candy',
+      method: () => this.stuff,  // Returns 'fruit'
+    };
+  }
+}
+
+ +

5.3.6 Shorthand properties

+ +

Shorthand properties are allowed on object literals.

+ +

Example:

+ +
const foo = 1;
+const bar = 2;
+const obj = {
+  foo,
+  bar,
+  method() { return this.foo + this.bar; },
+};
+assertEquals(3, obj.method());
+
+ +

5.3.7 Destructuring

+ +

Object destructuring patterns may be used on the left-hand side of an assignment +to perform destructuring and unpack multiple values from a single object.

+ +

Destructured objects may also be used as function parameters, but should be kept +as simple as possible: a single level of unquoted shorthand properties. Deeper +levels of nesting and computed properties may not be used in parameter +destructuring. Specify any default values in the left-hand-side of the +destructured parameter ({str = 'some default'} = {}, rather than {str} = {str: 'some default'}), and if a destructured +object is itself optional, it must default to {}. The JSDoc for the +destructured parameter may be given any name (the name is unused but is required +by the compiler).

+ +

Example:

+ +
/**
+ * @param {string} ordinary
+ * @param {{num: (number|undefined), str: (string|undefined)}=} param1
+ *     num: The number of times to do something.
+ *     str: A string to do stuff to.
+ */
+function destructured(ordinary, {num, str = 'some default'} = {})
+
+ +

Illegal:

+ +
/** @param {{x: {num: (number|undefined), str: (string|undefined)}}} param1 */
+function nestedTooDeeply({x: {num, str}}) {};
+/** @param {{num: (number|undefined), str: (string|undefined)}=} param1 */
+function nonShorthandProperty({num: a, str: b} = {}) {};
+/** @param {{a: number, b: number}} param1 */
+function computedKey({a, b, [a + b]: c}) {};
+/** @param {{a: number, b: string}=} param1 */
+function nontrivialDefault({a, b} = {a: 2, b: 4}) {};
+
+ +

Destructuring may also be used for goog.require statements, and in this case +must not be wrapped: the entire statement occupies one line, regardless of how +long it is (see ??).

+ +

5.3.8 Enums

+ +

Enumerations are defined by adding the @enum annotation to an object literal. +Additional properties may not be added to an enum after it is defined. Enums +must be constant, and all enum values must be deeply immutable.

+ +
/**
+ * Supported temperature scales.
+ * @enum {string}
+ */
+const TemperatureScale = {
+  CELSIUS: 'celsius',
+  FAHRENHEIT: 'fahrenheit',
+};
+
+/**
+ * An enum with two options.
+ * @enum {number}
+ */
+const Option = {
+  /** The option used shall have been the first. */
+  FIRST_OPTION: 1,
+  /** The second among two options. */
+  SECOND_OPTION: 2,
+};
+
+ +

5.4 Classes

+ +

5.4.1 Constructors

+ +

Constructors are optional for concrete classes, and when present must be the +first method defined in the class literal. Subclass constructors must call +super() before setting any fields or otherwise accessing this. Interfaces +must not define a constructor.

+ +

5.4.2 Fields

+ +

Set all of a concrete object’s fields (i.e. all properties other than methods) +in the constructor. Annotate fields that are never reassigned with @const +(these need not be deeply immutable). Private fields must be annotated with +@private and their names must end with a trailing underscore. Fields are never +set on a concrete class' prototype.

+ +

Example:

+ +
class Foo {
+  constructor() {
+    /** @private @const {!Bar} */
+    this.bar_ = computeBar();
+  }
+}
+
+ +

Tip: Properties should never be added to or removed from an instance after the +constructor is finished, since it significantly hinders VMs’ ability to +optimize. If necessary, fields that are initialized later should be explicitly +set to undefined in the constructor to prevent later shape changes. Adding +@struct to an object will check that undeclared properties are not +added/accessed. Classes have this added by default.

+ +

5.4.3 Computed properties

+ + + +

Computed properties may only be used in classes when the property is a +symbol. Dict-style properties (that is, quoted or computed non-symbol keys, as +defined in ??) are not allowed. A +[Symbol.iterator] method should be defined for any classes that are logically +iterable. Beyond this, Symbol should be used sparingly.

+ +

Tip: be careful of using any other built-in symbols (e.g., Symbol.isConcatSpreadable) as they are not polyfilled by the compiler and will therefore not work in older browsers.

+ +

5.4.4 Static methods

+ + + +

Where it does not interfere with readability, prefer module-local functions over +private static methods.

+ +

Static methods should only be called on the base class itself. Static methods +should not be called on variables containing a dynamic instance that may be +either the constructor or a subclass constructor (and must be defined with +@nocollapse if this is done), and must not be called directly on a subclass +that doesn’t define the method itself.

+ +

Illegal:

+ +
class Base { /** @nocollapse */ static foo() {} }
+class Sub extends Base {}
+function callFoo(cls) { cls.foo(); }  // discouraged: don't call static methods dynamically
+Sub.foo();  // illegal: don't call static methods on subclasses that don't define it themselves
+
+ +

5.4.5 Old-style class declarations

+ +

Old-style class declarations (either using a /** @constructor */-annotated function, or else goog.defineClass) are not allowed.

+ +

5.4.6 Do not manipulate prototypes directly

+ +

The class keyword allows clearer and more readable class definitions than +defining prototype properties. Ordinary implementation code has no business +manipulating these objects, though they are still useful for defining @record +interfaces. Mixins and modifying the prototypes of builtin objects are +explicitly forbidden.

+ +

Exception: Framework code (such as Polymer, or Angular) may need to use prototypes, and should not +resort to even-worse workarounds to avoid doing so.

+ +

5.4.7 Getters and Setters

+ +

Do not use JavaScript getter and setter properties. They are potentially +surprising and difficult to reason about, and have limited support in the +compiler. Provide ordinary methods instead.

+ +

Exception: when working with data binding frameworks (such as Angular and +Polymer), getters and setters may be used sparingly. Note, however, that +compiler support is limited. When they are used, they must be defined either +with get foo() and set foo(value) in the class or object literal, or if that +is not possible, with Object.defineProperties. Do not use +Object.defineProperty, which interferes with property renaming. Getters +must not change observable state.

+ +

Illegal:

+ +
class Foo {
+  get next() { return this.nextId++; }
+}
+
+ +

5.4.8 Overriding toString

+ +

The toString method may be overridden, but must always succeed and never have +visible side effects.

+ +

Tip: Beware, in particular, of calling other methods from toString, since +exceptional conditions could lead to infinite loops.

+ +

5.4.9 Interfaces

+ +

Interfaces may be declared with @interface or @record. Interfaces declared +with @record can be explicitly (i.e. via @implements) or implicitly +implemented by a class or object literal. In particular, do not use a @typedef +to define a record literal.

+ +

All non-static method bodies on an interface must be empty blocks. Fields must +be defined after the interface body as stubs on the prototype.

+ +

Example:

+ +
/**
+ * Something that can frobnicate.
+ * @record
+ */
+class Frobnicator {
+  /**
+   * Performs the frobnication according to the given strategy.
+   * @param {!FrobnicationStrategy} strategy
+   */
+  frobnicate(strategy) {}
+}
+
+/** @type {number} The number of attempts before giving up. */
+Frobnicator.prototype.attempts;
+
+ +

5.5 Functions

+ +

5.5.1 Top-level functions

+ +

Exported functions may be defined directly on the exports object, or else +declared locally and exported separately. Non-exported functions are encouraged +and should not be declared @private.

+ +

Examples:

+ +
/** @return {number} */
+function helperFunction() {
+  return 42;
+}
+/** @return {number} */
+function exportedFunction() {
+  return helperFunction() * 2;
+}
+/**
+ * @param {string} arg
+ * @return {number}
+ */
+function anotherExportedFunction(arg) {
+  return helperFunction() / arg.length;
+}
+/** @const */
+exports = {exportedFunction, anotherExportedFunction};
+
+ +
/** @param {string} arg */
+exports.foo = (arg) => {
+  // do some stuff ...
+};
+
+ +

5.5.2 Nested functions and closures

+ +

Functions may contain nested function definitions. If it is useful to give the +function a name, it should be assigned to a local const.

+ +

5.5.3 Arrow functions

+ +

Arrow functions provide a concise syntax and fix a number of difficulties with +this. Prefer arrow functions over the function keyword, particularly for +nested functions (but see ??).

+ +

Never call f.bind(this) or goog.bind(f, this) (and avoid writing const self += this). All of these can be expressed more clearly and less error-prone with +an arrow function. This is particularly useful for callbacks, which sometimes +pass unexpected additional arguments.

+ +

The right-hand side of the arrow may be a single expression or a block. +Parentheses around the arguments are optional if there is only a single +non-destructured argument.

+ +

Tip: It is a good practice to use parentheses even for single-argument arrows, +since the code may still parse reasonably (but incorrectly) if the parentheses +are forgotten when an additional argument is added.

+ +

5.5.4 Generators

+ +

Generators enable a number of useful abstractions and may be used as needed.

+ +

When defining generator functions, attach the * to the function keyword when +present, and separate it with a space from the name of the function. When using +delegating yields, attach the * to the yield keyword.

+ +

Example:

+ +
/** @return {!Iterator<number>} */
+function* gen1() {
+  yield 42;
+}
+
+/** @return {!Iterator<number>} */
+const gen2 = function*() {
+  yield* gen1();
+}
+
+class SomeClass {
+  /** @return {!Iterator<number>} */
+  * gen() {
+    yield 42;
+  }
+}
+
+ +

5.5.5 Parameters

+ +

Function parameters must be typed with JSDoc annotations in the JSDoc preceding +the function’s definition, except in the case of same-signature @overrides, +where all types are omitted.

+ +

For anonymous functions (arrows and unnamed function expressions), parameter +types may be specified inline, immediately before the parameter name (as in +(/** number */ foo, /** string */ bar) => foo + bar). This is not allowed for +other functions, including class methods and those that are assigned to +variables or properties, in which case the parameter and/or return type +annotations must be specified on the field, variable, or method.

+ +

Illegal:

+ +
const func = (/** number */ foo) => 2 * foo;  // use ordinary @param instead
+
+ +
5.5.5.1 Default parameters
+ +

Optional parameters are permitted using the equals operator in the parameter +list. Optional parameters must include spaces on both sides of the equals +operator, be named exactly like required parameters (i.e., not prefixed with +opt_), use the = suffix in their JSDoc type, come after required parameters, +and not use initializers that produce observable side effects. All optional +parameters must have a default value in the function declaration, even if that +value is undefined.

+ +

Example:

+ +
/**
+ * @param {string} required This parameter is always needed.
+ * @param {string=} optional This parameter can be omitted.
+ * @param {!Node=} node Another optional parameter.
+ */
+function maybeDoSomething(required, optional = '', node = undefined) {}
+
+ +

Use default parameters sparingly. Prefer destructuring (as in +??) to create readable APIs when there +are more than a small handful of optional parameters that do not have a natural +order.

+ +

Note: Unlike Python's default parameters, it is okay to use initializers that +return new mutable objects (such as {} or []) because the initializer is +evaluated each time the default value is used, so a single object won't be +shared across invocations.

+ +

Tip: While arbitrary expressions including function calls may be used as +initializers, these should be kept as simple as possible. Avoid initializers +that expose shared mutable state, as that can easily introduce unintended +coupling between function calls.

+ +
5.5.5.2 Rest parameters
+ +

Use a rest parameter instead of accessing arguments. Rest parameters are +typed with a ... prefix in their JSDoc. The rest parameter must be the last +parameter in the list. There is no space between the ... and the parameter +name. Do not name the rest parameter var_args. Never name a local variable or +parameter arguments, which confusingly shadows the built-in name.

+ +

Example:

+ +
/**
+ * @param {!Array<string>} array This is an ordinary parameter.
+ * @param {...number} numbers The remainder of arguments are all numbers.
+ */
+function variadic(array, ...numbers) {}
+
+ +

5.5.6 Returns

+ +

Function return types must be specified in the JSDoc directly above the function +definition, except in the case of same-signature @overrides where all types +are omitted.

+ +

5.5.7 Generics

+ +

Declare generic functions and methods when necessary with @template TYPE in +the JSDoc above the class definition.

+ +

5.5.8 Spread operator

+ +

Function calls may use the spread operator (...). Prefer the spread operator +to Function.prototype.apply when an array or iterable is unpacked into +multiple parameters of a variadic function. There is no space after the ....

+ +

Example:

+ +
function myFunction(...elements) {}
+myFunction(...array, ...iterable, ...generator());
+
+ +

5.6 String literals

+ +

5.6.1 Use single quotes

+ +

Ordinary string literals are delimited with single quotes ('), rather than +double quotes (").

+ +

Tip: if a string contains a single quote character, consider using a template +string to avoid having to escape the quote.

+ +

Ordinary string literals may not span multiple lines.

+ +

5.6.2 Template strings

+ +

Use template strings (delimited with `) over complex string +concatenation, particularly if multiple string literals are involved. Template +strings may span multiple lines.

+ +

If a template string spans multiple lines, it does not need to follow the +indentation of the enclosing block, though it may if the added whitespace does +not matter.

+ +

Example:

+ +
function arithmetic(a, b) {
+  return `Here is a table of arithmetic operations:
+${a} + ${b} = ${a + b}
+${a} - ${b} = ${a - b}
+${a} * ${b} = ${a * b}
+${a} / ${b} = ${a / b}`;
+}
+
+ +

5.6.3 No line continuations

+ +

Do not use line continuations (that is, ending a line inside a string literal +with a backslash) in either ordinary or template string literals. Even though +ES5 allows this, it can lead to tricky errors if any trailing whitespace comes +after the slash, and is less obvious to readers.

+ +

Illegal:

+ +
const longString = 'This is a very long string that far exceeds the 80 \
+    column limit. It unfortunately contains long stretches of spaces due \
+    to how the continued lines are indented.';
+
+ +

Instead, write

+ +
const longString = 'This is a very long string that far exceeds the 80 ' +
+    'column limit. It does not contains long stretches of spaces since ' +
+    'the concatenated strings are cleaner.';
+
+ +

5.7 Number literals

+ +

Numbers may be specified in decimal, hex, octal, or binary. Use exactly 0x, +0o, and 0b prefixes, with lowercase letters, for hex, octal, and binary, +respectively. Never include a leading zero unless it is immediately followed by +x, o, or b.

+ +

5.8 Control structures

+ +

5.8.1 For loops

+ +

With ES6, the language now has three different kinds of for loops. All may be +used, though for-of loops should be preferred when possible.

+ +

for-in loops may only be used on dict-style objects (see +??), and should not be used to iterate over an +array. Object.prototype.hasOwnProperty should be used in for-in loops to +exclude unwanted prototype properties. Prefer for-of and Object.keys over +for-in when possible.

+ +

5.8.2 Exceptions

+ +

Exceptions are an important part of the language and should be used whenever +exceptional cases occur. Always throw Errors or subclasses of Error: never +throw string literals or other objects. Always use new when constructing an +Error.

+ +

Custom exceptions provide a great way to convey additional error information +from functions. They should be defined and used wherever the native Error +type is insufficient.

+ +

Prefer throwing exceptions over ad-hoc error-handling approaches (such as +passing an error container reference type, or returning an object with an error +property).

+ +
5.8.2.1 Empty catch blocks
+ +

It is very rarely correct to do nothing in response to a caught exception. When +it truly is appropriate to take no action whatsoever in a catch block, the +reason this is justified is explained in a comment.

+ +
try {
+  return handleNumericResponse(response);
+} catch (ok) {
+  // it's not numeric; that's fine, just continue
+}
+return handleTextResponse(response);
+
+ +

Illegal:

+ +
   try {
+    shouldFail();
+    fail('expected an error');
+  }
+  catch (expected) {}
+
+ +

Tip: Unlike in some other languages, patterns like the above simply don’t work +since this will catch the error thrown by fail. Use assertThrows() instead.

+ +

5.8.3 Switch statements

+ +

Terminology Note: Inside the braces of a switch block are one or more statement groups. Each statement group consists of one or more switch labels (either case FOO: or default:), followed by one or more statements.

+ +
5.8.3.1 Fall-through: commented
+ +

Within a switch block, each statement group either terminates abruptly (with a +break, return or thrown exception), or is marked with a comment to +indicate that execution will or might continue into the next statement +group. Any comment that communicates the idea of fall-through is sufficient +(typically // fall through). This special comment is not required in the last +statement group of the switch block.

+ +

Example:

+ +
switch (input) {
+  case 1:
+  case 2:
+    prepareOneOrTwo();
+    // fall through
+  case 3:
+    handleOneTwoOrThree();
+    break;
+  default:
+    handleLargeNumber(input);
+}
+
+ +
5.8.3.2 The default case is present
+ +

Each switch statement includes a default statement group, even if it contains +no code.

+ +

5.9 this

+ +

Only use this in class constructors and methods, or in arrow functions defined +within class constructors and methods. Any other uses of this must have an +explicit @this declared in the immediately-enclosing function’s JSDoc.

+ +

Never use this to refer to the global object, the context of an eval, the +target of an event, or unnecessarily call()ed or apply()ed functions.

+ +

5.10 Disallowed features

+ +

5.10.1 with

+ +

Do not use the with keyword. It makes your code harder to understand and has +been banned in strict mode since ES5.

+ +

5.10.2 Dynamic code evaluation

+ +

Do not use eval or the Function(...string) constructor (except for code +loaders). These features are potentially dangerous and simply do not work in +CSP environments.

+ +

5.10.3 Automatic semicolon insertion

+ +

Always terminate statements with semicolons (except function and class +declarations, as noted above).

+ +

5.10.4 Non-standard features

+ +

Do not use non-standard features. This includes old features that have been +removed (e.g., WeakMap.clear), new features that are not yet standardized +(e.g., the current TC39 working draft, proposals at any stage, or proposed but +not-yet-complete web standards), or proprietary features that are only +implemented in some browsers. Use only features defined in the current ECMA-262 +or WHATWG standards. (Note that projects writing against specific APIs, such as +Chrome extensions or Node.js, can obviously use those APIs). Non-standard +language “extensions” (such as those provided by some external transpilers) are +forbidden.

+ +

5.10.5 Wrapper objects for primitive types

+ +

Never use new on the primitive object wrappers (Boolean, Number, String, +Symbol), nor include them in type annotations.

+ +

Illegal:

+ +
const /** Boolean */ x = new Boolean(false);
+if (x) alert(typeof x);  // alerts 'object' - WAT?
+
+ +

The wrappers may be called as functions for coercing (which is preferred over +using + or concatenating the empty string) or creating symbols.

+ +

Example:

+ +
const /** boolean */ x = Boolean(0);
+if (!x) alert(typeof x);  // alerts 'boolean', as expected
+
+ +

5.10.6 Modifying builtin objects

+ +

Never modify builtin types, either by adding methods to their constructors or to +their prototypes. Avoid depending on libraries that do this. Note that the +JSCompiler’s runtime library will provide standards-compliant polyfills where +possible; nothing else may modify builtin objects.

+ +

Do not add symbols to the global object unless absolutely necessary +(e.g. required by a third-party API).

+ +

6 Naming

+ +

6.1 Rules common to all identifiers

+ +

Identifiers use only ASCII letters and digits, and, in a small number of cases +noted below, underscores and very rarely (when required by frameworks like +Angular) dollar signs.

+ +

Give as descriptive a name as possible, within reason. Do not worry about saving +horizontal space as it is far more important to make your code immediately +understandable by a new reader. Do not use abbreviations that are ambiguous or +unfamiliar to readers outside your project, and do not abbreviate by deleting +letters within a word.

+ +
priceCountReader      // No abbreviation.
+numErrors             // "num" is a widespread convention.
+numDnsConnections     // Most people know what "DNS" stands for.
+
+ +

Illegal:

+ +
n                     // Meaningless.
+nErr                  // Ambiguous abbreviation.
+nCompConns            // Ambiguous abbreviation.
+wgcConnections        // Only your group knows what this stands for.
+pcReader              // Lots of things can be abbreviated "pc".
+cstmrId               // Deletes internal letters.
+kSecondsPerDay        // Do not use Hungarian notation.
+
+ +

6.2 Rules by identifier type

+ +

6.2.1 Package names

+ +

Package names are all lowerCamelCase. For example, +my.exampleCode.deepSpace, but not my.examplecode.deepspace or my.example_code.deep_space.

+ +
6.2.1.1 Hierarchy
+ +

Module namespaces may never be named as a direct child of another namespace.

+ +

Illegal:

+ +
goog.module('foo.bar');   // 'foo.bar.qux' would be fine, though
+goog.module('foo.bar.baz');
+
+ +

The directory hierarchy reflects the namespace hierarchy, so that deeper-nested +children are subdirectories of higher-level parent directories. Note that this +implies that owners of “parent” namespace groups are necessarily aware of all +child namespaces, since they exist in the same directory.

+ +

+ + + +

+ +

+ +
goog.module('googleyhats.BowlerHat');  // internal name
+
+const RoundHat = goog.require('foo.hats.RoundHat');  // external name
+
+const BowlerHat = class extends RoundHat {
+  …
+};
+exports = BowlerHat;
+
+goog.exportSymbol('foo.hats.BowlerHat', BowlerHat);  // export external name
+
+ +

+ +

+ +

6.2.2 Class names

+ +

Class, interface, record, and typedef names are written in UpperCamelCase. +Unexported classes are simply locals: they are not marked @private and +therefore are not named with a trailing underscore.

+ +

Type names are typically nouns or noun phrases. For example, Request, +ImmutableList, or VisibilityMode. Additionally, interface names may +sometimes be adjectives or adjective phrases instead (for example, Readable).

+ +

6.2.3 Method names

+ +

Method names are written in lowerCamelCase. Private methods’ names must end +with a trailing underscore.

+ +

Method names are typically verbs or verb phrases. For example, sendMessage or +stop_. Getter and setter methods for properties are never required, but if +they are used they should be named getFoo (or optionally isFoo or hasFoo +for booleans), or setFoo(value) for setters.

+ +

Underscores may also appear in JsUnit test method names to separate logical +components of the name. One typical pattern is test<MethodUnderTest>_<state>, +for example testPop_emptyStack. There is no One Correct Way to name test +methods.

+ +

6.2.4 Enum names

+ +

Enum names are written in UpperCamelCase, similar to classes, and should +generally be singular nouns. Individual items within the enum are named in +CONSTANT_CASE.

+ +

6.2.5 Constant names

+ +

Constant names use CONSTANT_CASE: all uppercase letters, with words separated +by underscores. There is no reason for a constant to be named with a trailing +underscore, since private static properties can be replaced by (implicitly +private) module locals.

+ +
6.2.5.1 Definition of “constant”
+ +

Every constant is a @const static property or a module-local const +declaration, but not all @const static properties and module-local consts +are constants. Before choosing constant case, consider whether the field really +feels like a deeply immutable constant. For example, if any of that instance's +observable state can change, it is almost certainly not a constant. Merely +intending to never mutate the object is generally not enough.

+ +

Examples:

+ +
// Constants
+const NUMBER = 5;
+/** @const */ exports.NAMES = ImmutableList.of('Ed', 'Ann');
+/** @enum */ exports.SomeEnum = { ENUM_CONSTANT: 'value' };
+
+// Not constants
+let letVariable = 'non-const';
+class MyClass { constructor() { /** @const */ this.nonStatic = 'non-static'; } };
+/** @type {string} */ MyClass.staticButMutable = 'not @const, can be reassigned';
+const /** Set<String> */ mutableCollection = new Set();
+const /** ImmutableSet<SomeMutableType> */ mutableElements = ImmutableSet.of(mutable);
+const Foo = goog.require('my.Foo');  // mirrors imported name
+const logger = log.getLogger('loggers.are.not.immutable');
+
+ +

Constants’ names are typically nouns or noun phrases.

+ +
6.2.5.1 Local aliases
+ +

Local aliases should be used whenever they improve readability over +fully-qualified names. Follow the same rules as goog.requires +(??), maintaining the last part of the aliased name. +Aliases may also be used within functions. Aliases must be const.

+ +

Examples:

+ +
const staticHelper = importedNamespace.staticHelper;
+const CONSTANT_NAME = ImportedClass.CONSTANT_NAME;
+const {assert, assertInstanceof} = asserts;
+
+ +

6.2.6 Non-constant field names

+ +

Non-constant field names (static or otherwise) are written in lowerCamelCase, +with a trailing underscore for private fields.

+ +

These names are typically nouns or noun phrases. For example, computedValues +or index_.

+ +

6.2.7 Parameter names

+ +

Parameter names are written in lowerCamelCase. Note that this applies even if +the parameter expects a constructor.

+ +

One-character parameter names should not be used in public methods.

+ +

Exception: When required by a third-party framework, parameter names may +begin with a $. This exception does not apply to any other identifiers +(e.g. local variables or properties).

+ +

6.2.8 Local variable names

+ +

Local variable names are written in lowerCamelCase, except for module-local +(top-level) constants, as described above. Constants in function scopes are +still named in lowerCamelCase. Note that lowerCamelCase applies even if the +variable holds a constructor.

+ +

6.2.9 Template parameter names

+ +

Template parameter names should be concise, single-word or single-letter +identifiers, and must be all-caps, such as TYPE or THIS.

+ +

6.3 Camel case: defined

+ +

Sometimes there is more than one reasonable way to convert an English phrase +into camel case, such as when acronyms or unusual constructs like IPv6 or +iOS are present. To improve predictability, Google Style specifies the +following (nearly) deterministic scheme.

+ +

Beginning with the prose form of the name:

+ +
    +
  1. Convert the phrase to plain ASCII and remove any apostrophes. For example, +Müller's algorithm might become Muellers algorithm.
  2. +
  3. Divide this result into words, splitting on spaces and any remaining +punctuation (typically hyphens). +
      +
    1. Recommended: if any word already has a conventional camel case +appearance in common usage, split this into its constituent parts (e.g., +AdWords becomes ad words). Note that a word such as iOS is not +really in camel case per se; it defies any convention, so this +recommendation does not apply.
    2. +
  4. +
  5. Now lowercase everything (including acronyms), then uppercase only the first +character of: +
      +
    1. … each word, to yield upper camel case, or
    2. +
    3. … each word except the first, to yield lower camel case
    4. +
  6. +
  7. Finally, join all the words into a single identifier.
  8. +
+ +

Note that the casing of the original words is almost entirely disregarded.

+ +

Examples:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Prose formCorrectIncorrect
XML HTTP requestXmlHttpRequestXMLHTTPRequest
new customer IDnewCustomerIdnewCustomerID
inner stopwatchinnerStopwatchinnerStopWatch
supports IPv6 on iOS?supportsIpv6OnIossupportsIPv6OnIOS
YouTube importerYouTubeImporterYoutubeImporter*
+ +

*Acceptable, but not recommended.

+ +

Note: Some words are ambiguously hyphenated in the English language: for example nonempty and non-empty are both correct, so the method names checkNonempty and checkNonEmpty are likewise both correct.

+ +

7 JSDoc

+ +

JSDoc is used on all classes, fields, and methods.

+ +

7.1 General form

+ +

The basic formatting of JSDoc blocks is as seen in this example:

+ +
/**
+ * Multiple lines of JSDoc text are written here,
+ * wrapped normally.
+ * @param {number} arg A number to do something to.
+ */
+function doSomething(arg) { … }
+
+ +

or in this single-line example:

+ +
/** @const @private {!Foo} A short bit of JSDoc. */
+this.foo_ = foo;
+
+ +

If a single-line comment overflows into multiple lines, it must use the +multi-line style with /** and */ on their own lines.

+ +

Many tools extract metadata from JSDoc comments to perform code validation and +optimization. As such, these comments must be well-formed.

+ +

7.2 Markdown

+ +

JSDoc is written in Markdown, though it may include HTML when necessary.

+ +

Note that tools that automatically extract JSDoc (e.g. JsDossier) will often +ignore plain text formatting, so if you did this:

+ +
/**
+ * Computes weight based on three factors:
+ *   items sent
+ *   items received
+ *   last timestamp
+ */
+
+ +

it would come out like this:

+ +
Computes weight based on three factors: items sent items received last timestamp
+
+ +

Instead, write a Markdown list:

+ +
/**
+ * Computes weight based on three factors:
+ *  - items sent
+ *  - items received
+ *  - last timestamp
+ */
+
+ +

7.3 JSDoc tags

+ +

Google style allows a subset of JSDoc tags. See +?? for the complete list. Most tags must +occupy their own line, with the tag at the beginning of the line.

+ +

Illegal:

+ +
/**
+ * The "param" tag must occupy its own line and may not be combined.
+ * @param {number} left @param {number} right
+ */
+function add(left, right) { ... }
+
+ +

Simple tags that do not require any additional data (such as @private, +@const, @final, @export) may be combined onto the same line, along with an +optional type when appropriate.

+ +
/**
+ * Place more complex annotations (like "implements" and "template")
+ * on their own lines.  Multiple simple tags (like "export" and "final")
+ * may be combined in one line.
+ * @export @final
+ * @implements {Iterable<TYPE>}
+ * @template TYPE
+ */
+class MyClass {
+  /**
+   * @param {!ObjType} obj Some object.
+   * @param {number=} num An optional number.
+   */
+  constructor(obj, num = 42) {
+    /** @private @const {!Array<!ObjType|number>} */
+    this.data_ = [obj, num];
+  }
+}
+
+ +

There is no hard rule for when to combine tags, or in which order, but be +consistent.

+ +

For general information about annotating types in JavaScript see +Annotating JavaScript for the Closure Compiler and Types in the Closure Type +System.

+ +

7.4 Line wrapping

+ +

Line-wrapped block tags are indented four spaces. Wrapped description text may +be lined up with the description on previous lines, but this horizontal +alignment is discouraged.

+ +
/**
+ * Illustrates line wrapping for long param/return descriptions.
+ * @param {string} foo This is a param with a description too long to fit in
+ *     one line.
+ * @return {number} This returns something that has a description too long to
+ *     fit in one line.
+ */
+exports.method = function(foo) {
+  return 5;
+};
+
+ +

Do not indent when wrapping a @fileoverview description.

+ +

7.5 Top/file-level comments

+ +

A file may have a top-level file overview. A copyright notice , author information, and +default visibility level are optional. File overviews are generally recommended whenever a +file consists of more than a single class definition. The top level comment is +designed to orient readers unfamiliar with the code to what is in this file. If +present, it may provide a description of the file's contents and any +dependencies or compatibility information. Wrapped lines are not indented.

+ +

Example:

+ +
/**
+ * @fileoverview Description of file, its uses and information
+ * about its dependencies.
+ * @package
+ */
+
+ +

7.6 Class comments

+ +

Classes, interfaces and records must be documented with a description and any +template parameters, implemented interfaces, visibility, or other appropriate +tags. The class description should provide the reader with enough information to +know how and when to use the class, as well as any additional considerations +necessary to correctly use the class. Textual descriptions may be omitted on the +constructor. @constructor and @extends annotations are not used with the +class keyword unless the class is being used to declare an @interface or +it extends a generic class.

+ +
/**
+ * A fancier event target that does cool things.
+ * @implements {Iterable<string>}
+ */
+class MyFancyTarget extends EventTarget {
+  /**
+   * @param {string} arg1 An argument that makes this more interesting.
+   * @param {!Array<number>} arg2 List of numbers to be processed.
+   */
+  constructor(arg1, arg2) {
+    // ...
+  }
+};
+
+/**
+ * Records are also helpful.
+ * @extends {Iterator<TYPE>}
+ * @record
+ * @template TYPE
+ */
+class Listable {
+  /** @return {TYPE} The next item in line to be returned. */
+  next() {}
+}
+
+ +

7.7 Enum and typedef comments

+ +

Enums and typedefs must be documented. Public enums and typedefs must have a +non-empty description. Individual enum items may be documented with a JSDoc +comment on the preceding line.

+ +
/**
+ * A useful type union, which is reused often.
+ * @typedef {!Bandersnatch|!BandersnatchType}
+ */
+let CoolUnionType;
+
+
+/**
+ * Types of bandersnatches.
+ * @enum {string}
+ */
+const BandersnatchType = {
+  /** This kind is really frumious. */
+  FRUMIOUS: 'frumious',
+  /** The less-frumious kind. */
+  MANXOME: 'manxome',
+};
+
+ +

Typedefs should be limited to defining aliases for unions or complex function or +generic types, and should be avoided for record literals (e.g. @typedef {{foo: +number, bar: string}}) since it does not allow documenting individual fields, +nor using templates or recursive references. Prefer @record for anything +beyond the simplest @typedef’d record literal.

+ +

7.8 Method and function comments

+ +

Parameter and return types must be documented. The this type should be +documented when necessary. Method, parameter, and return descriptions (but not +types) may be omitted if they are obvious from the rest of the method’s JSDoc or +from its signature. Method descriptions should start with a sentence written in +the third person declarative voice. If a method overrides a superclass method, +it must include an @override annotation. Overridden methods must include all +@param and @return annotations if any types are refined, but should omit +them if the types are all the same.

+ +
/** This is a class. */
+class SomeClass extends SomeBaseClass {
+  /**
+   * Operates on an instance of MyClass and returns something.
+   * @param {!MyClass} obj An object that for some reason needs detailed
+   *     explanation that spans multiple lines.
+   * @param {!OtherClass} obviousOtherClass
+   * @return {boolean} Whether something occurred.
+   */
+  someMethod(obj, obviousOtherClass) { ... }
+
+  /** @override */
+  overriddenMethod(param) { ... }
+}
+
+/**
+ * Top-level functions follow the same rules.  This one makes an array.
+ * @param {TYPE} arg
+ * @return {!Array<TYPE>}
+ * @template TYPE
+ */
+function makeArray(arg) { ... }
+
+ + + +

Anonymous functions do not require JSDoc, though parameter types may be specified inline if the automatic type inference is insufficient.

+ +
promise.then(
+    (/** !Array<number|string> */ items) => {
+      doSomethingWith(items);
+      return /** @type {string} */ (items[0]);
+    });
+
+ +

7.9 Property comments

+ +

Property types must be documented. The description may be omitted for private +properties, if name and type provide enough documentation for understanding the +code.

+ +

Publicly exported constants are commented the same way as properties. Explicit +types may be omitted for @const properties initialized from an expression with +an obviously known type.

+ +

Tip: A @const property’s type can be considered “obviously known” if it is +assigned directly from a constructor parameter with a declared type, or directly +from a function call with a declared return type. Non-const properties and +properties assigned from more complex expressions should have their types +declared explicitly.

+ +
/** My class. */
+class MyClass {
+  /** @param {string=} someString */
+  constructor(someString = 'default string') {
+    /** @private @const */
+    this.someString_ = someString;
+
+    /** @private @const {!OtherType} */
+    this.someOtherThing_ = functionThatReturnsAThing();
+
+    /**
+     * Maximum number of things per pane.
+     * @type {number}
+     */
+    this.someProperty = 4;
+  }
+}
+
+/**
+ * The number of times we'll try before giving up.
+ * @const
+ */
+MyClass.RETRY_COUNT = 33;
+
+ +

7.10 Type annotations

+ +

Type annotations are found on @param, @return, @this, and @type tags, +and optionally on @const, @export, and any visibility tags. Type +annotations attached to JSDoc tags must always be enclosed in braces.

+ +

7.10.1 Nullability

+ +

The type system defines modifiers ! and ? for non-null and nullable, +respectively. Primitive types (undefined, string, number, boolean, +symbol, and function(...): ...) and record literals ({foo: string, bar: +number}) are non-null by default. Do not add an explicit ! to these types. +Object types (Array, Element, MyClass, etc) are nullable by default, but +cannot be immediately distinguished from a name that is @typedef’d to a +non-null-by-default type. As such, all types except primitives and record +literals must be annotated explicitly with either ? or ! to indicate whether +they are nullable or not.

+ +

7.10.2 Type Casts

+ +

In cases where type checking doesn't accurately infer the type of an expression, +it is possible to tighten the type by adding a type annotation comment and +enclosing the expression in parentheses. Note that the parentheses are required.

+ +
/** @type {number} */ (x)
+
+ +

7.10.3 Template Parameter Types

+ +

Always specify template parameters. This way compiler can do a better job and it +makes it easier for readers to understand what code does.

+ +

Bad:

+ +
/** @type {!Object} */ var users;
+/** @type {!Array} */ var books;
+/** @type {!Promise} */ var response;
+
+ +

Good:

+ +
/** @type {!Object<string, !User>} */ const users;
+/** @type {!Array<string>} */ const books;
+/** @type {!Promise<!Response>} */ const response;
+
+/** @type {!Promise<undefined>} */ const thisPromiseReturnsNothingButParameterIsStillUseful;
+/** @type {!Object<string, *>} */ const mapOfEverything;
+
+ +

Cases when template parameters should not be used:

+ + + +

7.11 Visibility annotations

+ +

Visibility annotations (@private, @package, @protected) may be specified +in a @fileoverview block, or on any exported symbol or property. Do not +specify visibility for local variables, whether within a function or at the top +level of a module. All @private names must end with an underscore.

+ +

8 Policies

+ +

8.1 Issues unspecified by Google Style: Be Consistent!

+ +

For any style question that isn't settled definitively by this specification, +prefer to do what the other code in the same file is already doing. If that +doesn't resolve the question, consider emulating the other files in the same +package.

+ + + +

+

+ +

+ +

8.2 Compiler warnings

+ +

8.2.1 Use a standard warning set

+ +

+ +

+As far as possible projects should use --warning_level=VERBOSE. +

+ +

8.2.2 How to handle a warning

+ +

Before doing anything, make sure you understand exactly what the warning is +telling you. If you're not positive why a warning is appearing, ask for help +.

+ +

Once you understand the warning, attempt the following solutions in order:

+ +
    +
  1. First, fix it or work around it. Make a strong attempt to actually +address the warning, or find another way to accomplish the task that avoids +the situation entirely.
  2. +
  3. Otherwise, determine if it's a false alarm. If you are convinced that +the warning is invalid and that the code is actually safe and correct, add a +comment to convince the reader of this fact and apply the @suppress +annotation.
  4. +
  5. Otherwise, leave a TODO comment. This is a last resort. If you do +this, do not suppress the warning. The warning should be visible until +it can be taken care of properly.
  6. +
+ +

8.2.3 Suppress a warning at the narrowest reasonable scope

+ +

Warnings are suppressed at the narrowest reasonable scope, usually that of a single local variable or very small method. Often a variable or method is extracted for that reason alone.

+ +

Example

+ +
/** @suppress {uselessCode} Unrecognized 'use asm' declaration */
+function fn() {
+  'use asm';
+  return 0;
+}
+
+ +

Even a large number of suppressions in a class is still better than blinding the +entire class to this type of warning.

+ +

8.3 Deprecation

+ +

Mark deprecated methods, classes or interfaces with @deprecated annotations. A +deprecation comment must include simple, clear directions for people to fix +their call sites.

+ +

+ +

+ +

+ +

8.4 Code not in Google Style

+ +

You will occasionally encounter files in your codebase that are not in proper +Google Style. These may have come from an acquisition, or may have been written +before Google Style took a position on some issue, or may be in non-Google Style +for any other reason.

+ +

8.4.1 Reformatting existing code

+ +

When updating the style of existing code, follow these guidelines.

+ +
    +
  1. It is not required to change all existing code to meet current style +guidelines. Reformatting existing code is a trade-off between code churn +and consistency. Style rules evolve over time and these kinds of tweaks to +maintain compliance would create unnecessary churn. However, if significant +changes are being made to a file it is expected that the file will be in +Google Style.
  2. +
  3. Be careful not to allow opportunistic style fixes to muddle the focus of a +CL. If you find yourself making a lot of style changes that aren’t critical +to the central focus of a CL, promote those changes to a separate CL.
  4. +
+ +

8.4.2 Newly added code: use Google Style

+ +

Brand new files use Google Style, regardless of the style choices of other files +in the same package.

+ +

When adding new code to a file that is not in Google Style, reformatting the +existing code first is recommended, subject to the advice in +??.

+ +

If this reformatting is not done, then new code should be as consistent as +possible with existing code in the same file, but must not violate the style +guide.

+ +

8.5 Local style rules

+ +

Teams and projects may adopt additional style rules beyond those in this +document, but must accept that cleanup changes may not abide by these additional +rules, and must not block such cleanup changes due to violating any additional +rules. Beware of excessive rules which serve no purpose. The style guide does +not seek to define style in every possible scenario and neither should you.

+ +

8.6 Generated code: mostly exempt

+ +

Source code generated by the build process is not required to be in Google +Style. However, any generated identifiers that will be referenced from +hand-written source code must follow the naming requirements. As a special +exception, such identifiers are allowed to contain underscores, which may help +to avoid conflicts with hand-written identifiers.

+ + + +

+ +

+

+ +

+ +

9 Appendices

+ +

9.1 JSDoc tag reference

+ +

JSDoc serves multiple purposes in JavaScript. In addition to being used to +generate documentation it is also used to control tooling. The best known are +the Closure Compiler type annotations.

+ +

9.1.1 Type annotations and other Closure Compiler annotations

+ +

Documentation for JSDoc used by the Closure Compiler is described in +Annotating JavaScript for the Closure Compiler and Types in the Closure Type +System.

+ +

9.1.2 Documentation annotations

+ +

In addition to the JSDoc described in Annotating JavaScript for the Closure +Compiler the following tags are common and well supported by various +documentation generations tools (such as JsDossier) for purely documentation +purposes. + + + + + + + + + +
Tag + Template & Examples + Description +
@author or @owner + @author username@google.com (First Last) +

For example: +

+/**
+ * @fileoverview Utilities for handling textareas.
+ * @author kuth@google.com (Uthur Pendragon)
+ */
+ 
+
Document the author of a file or the owner of a test, generally only + used in the @fileoverview comment. The @owner tag is used by the + unit test dashboard to determine who owns the test results. +

Not recommended. +

@bug + @bug bugnumber +

For example: +

+/** @bug 1234567 */
+function testSomething() {
+  // …
+}

+ +

/** + * @bug 1234568 + * @bug 1234569 + */ +function testTwoBugs() { + // … +} +

+
Indicates what bugs the given test function regression tests. +

Multiple bugs should each have their own @bug line, to make + searching for regression tests as easy as possible. +

@code + {@code ...} +

For example: +

+/**
+ * Moves to the next position in the selection.
+ * Throws {@code goog.iter.StopIteration} when it
+ * passes the end of the range.
+ * @return {!Node} The node at the next position.
+ */
+goog.dom.RangeIterator.prototype.next = function() {
+  // …
+};
+
+
Indicates that a term in a JSDoc description is code so it may be + correctly formatted in generated documentation. +
@see + @see Link +

For example: +

+/**
+ * Adds a single item, recklessly.
+ * @see #addSafely
+ * @see goog.Collect
+ * @see goog.RecklessAdder#add
+ */
+ 
+
Reference a lookup to another class function or method. +
@supported + @supported Description +

For example: +

+/**
+ * @fileoverview Event Manager
+ * Provides an abstracted interface to the
+ * browsers' event systems.
+ * @supported IE10+, Chrome, Safari
+ */
+
+
Used in a fileoverview to indicate what browsers are supported by + the file. +

+ +

You may also see other types of JSDoc annotations in third-party code. These +annotations appear in the JSDoc Toolkit Tag Reference but are not considered +part of valid Google style.

+ +

9.1.3 Framework specific annotations

+ +

The following annotations are specific to a particular framework. + + + + + + +
Framework + Tag + Documentation +
Angular 1 + @ngInject +
Polymer + @polymerBehavior + + + https://github.com/google/closure-compiler/wiki/Polymer-Pass + +

+ +

9.1.4 Notes about standard Closure Compiler annotations

+ +

The following tags used to be standard but are now deprecated. + + + + + + +
Tag + Template & Examples + Description +
@expose + @expose + Deprecated. Do not use. Use @export and/or @nocollapse + instead. +
@inheritDoc + @inheritDoc + Deprecated. Do not use. Use @override instead. +

+ + + +

+

+ + + +

+

+ +

9.2 Commonly misunderstood style rules

+ +

Here is a collection of lesser-known or commonly misunderstood facts about +Google Style for JavaScript. (The following are true statements; this is not a +list of myths.)

+ + + + + +

The following tools exist to support various aspects of Google Style.

+ +

9.4.1 Closure Compiler

+ +

This program performs type checking and other checks, +optimizations and other transformations (such as EcmaScript 6 to EcmaScript 5 +code lowering).

+ + + +

+ +

+ +

9.4.2 clang-format

+ +

+ +

This program reformats +JavaScript source code into Google Style, and also follows a number of +non-required but frequently readability-enhancing formatting practices.

+ +

clang-format is not required. Authors are allowed to change its output, and +reviewers are allowed to ask for such changes; disputes are worked out in the +usual way. However, subtrees may choose to opt in to such enforcement locally.

+ +

9.4.3 Closure compiler linter

+ +

+ +

This program checks for a +variety of missteps and anti-patterns. +

+ +

9.4.4 Conformance framework

+ +

The JS Conformance Framework is a tool that is part of the Closure Compiler that +provides developers a simple means to specify a set of additional checks to be +run against their code base above the standard checks. Conformance checks can, +for example, forbid access to a certain property, or calls to a certain +function, or missing type information (unknowns).

+ +

These rules are commonly used to enforce critical restrictions (such as defining +globals, which could break the codebase) and security patterns (such as using +eval or assigning to innerHTML), or more loosely to improve code quality.

+ +

For additional information see the official documentation for the +JS Conformance Framework.

+ + + +

+ +
tricorder: {
+  enable: JavaScript
+}
+
+ +

+ + + +

+

+
+ +