diff --git a/jsguide.html b/jsguide.html index 4da5bfa..af44f7f 100644 --- a/jsguide.html +++ b/jsguide.html @@ -13,7 +13,7 @@

Google JavaScript Style Guide

1 Introduction

-

This document serves as the complete definition of Google’s coding standards +

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.

@@ -30,8 +30,8 @@ we follow universally, and avoids giving advice that isn't clearly enforceable
  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 /** … +the phrase documentation comments, instead using the common term “JSDoc” +for both human-readable text and machine-readable annotations within /** … */.

  2. This Style Guide uses RFC 2119 terminology when using the phrases must, must not, should, should not, and may. The terms prefer and @@ -54,7 +54,7 @@ rules.

    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.

    +uses. Filenames’ extension must be .js.

    2.2 File encoding: UTF-8

    @@ -83,17 +83,17 @@ 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, +(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.

    /* Best: perfectly clear even without a comment. */
    -const units = 'μs';
    +const units = 'μs';
     
    -/* Allowed: but unnecessary as μ is a printable character. */
    -const units = '\u03bcs'; // 'μs'
    +/* Allowed: but unnecessary as μ is a printable character. */
    +const units = '\u03bcs'; // 'μs'
     
     /* Good: use escapes for non-printable characters with a comment for clarity. */
     return '\ufeff' + content;  // Prepend a byte order mark.
    @@ -121,7 +121,7 @@ file (a file containing a goog.module call) or an ECMAScript (ES) m
     
  3. goog.module statement, if a goog.module file
  4. ES import statements, if an ES module
  5. goog.require and goog.requireType statements
  6. -
  7. The file’s implementation
  8. +
  9. The file’s implementation

Exactly one blank line separates each section that is present, except the @@ -164,7 +164,7 @@ 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 +implies that owners of “parent” namespace groups are necessarily aware of all child namespaces, since they exist in the same directory.

3.3.2 goog.module.declareLegacyNamespace

@@ -592,7 +592,7 @@ destructuring requires, again sorted by the names on the left hand side. Finally, any require calls that are standalone (generally these are for modules imported just for their side effects).

-

Tip: There’s no need to memorize this order and enforce it manually. You can +

Tip: There’s no need to memorize this order and enforce it manually. You can rely on your IDE to report requires that are not sorted correctly.

@@ -670,7 +670,7 @@ function someFunction(param) { }
-

3.7 The file’s implementation

+

3.7 The file’s implementation

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

@@ -706,7 +706,7 @@ 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 +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.

@@ -762,13 +762,13 @@ multiple blocks: if/else or try/cat

Disallowed:

if (condition) {
-  // …
+  // …
 } else if (otherCondition) {} else {
-  // …
+  // …
 }
 
 try {
-  // …
+  // …
 } catch (e) {}
 
@@ -781,8 +781,8 @@ level. The indent level applies to both code and comments throughout the block.

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 +

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 = [
@@ -809,8 +809,8 @@ 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 +

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 = {
@@ -833,7 +833,7 @@ someMethod(foo, {
 
 

Class literals (whether declarations or expressions) are indented as blocks. Do not add semicolons after methods, or after the closing brace of a class -declaration (statements—such as assignments—that contain class expressions +declaration (statements—such as assignments—that contain class expressions are still terminated with a semicolon). For inheritance, the extends keyword is sufficient unless the superclass is templatized. Subclasses of templatized types must explicitly specify the template type in an @extends JSDoc @@ -1150,14 +1150,14 @@ most common patterns for argument wrapping:

// 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, @@ -1167,7 +1167,7 @@ doSomething( veryDescriptiveArgumentTwo, tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) { - // … + // … }
@@ -1192,7 +1192,7 @@ 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 +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.

@@ -1209,11 +1209,11 @@ comments obvious with no extra context.

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

-

Do not use JSDoc (/** … */) for implementation comments.

+

Do not use JSDoc (/** … */) for implementation comments.

4.8.2 Parameter Name Comments

-

“Parameter name” comments should be used whenever the value and method name do +

“Parameter name” comments should be used whenever the value and method name do not sufficiently convey the meaning, and refactoring the method to be clearer is infeasible . Their preferred format is before the value with =:

@@ -1354,15 +1354,15 @@ destructured array parameter is optional, and provide default values on the left hand side:

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

Disallowed:

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

Tip: For (un)packing multiple values into a function’s parameter or return, +

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.

@@ -1440,7 +1440,7 @@ 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 +{… }}) in place of a colon immediately followed by a function or arrow function literal.

Example:

@@ -1592,7 +1592,7 @@ non-method properties in the constructor.

5.4.2 Fields

-

Define all of a concrete object’s fields (i.e. all properties other than +

Define 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). Annotate non-public fields with the proper visibility annotation (@private, @protected, @package). @@ -1614,7 +1614,7 @@ be defined within a nested scope in the constructor nor on a concrete class's

Tip: Properties should never be added to or removed from an instance after the -constructor is finished, since it significantly hinders VMs’ ability to +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 @@ -1646,7 +1646,7 @@ interferes with Closure Compiler optimizations. 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 +and must not be called directly on a subclass that doesn’t define the method itself. Do not access this in static methods.

Disallowed:

@@ -2235,7 +2235,7 @@ return handleTextResponse(response); }
-

Tip: Unlike in some other languages, patterns like the above simply don’t work +

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

@@ -2277,7 +2277,7 @@ no code. The default statement group must be last.

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

+@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.

@@ -2324,7 +2324,7 @@ 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 +language “extensions” (such as those provided by some external transpilers) are forbidden.

5.11.5 Wrapper objects for primitive types

@@ -2351,7 +2351,7 @@ if (!x) alert(typeof x); // alerts 'boolean', as expected

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 +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. @@ -2461,7 +2461,7 @@ 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”
+
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 @@ -2496,7 +2496,7 @@ 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.

+

Constants’ names are typically nouns or noun phrases.

6.2.5.2 Local aliases
@@ -2560,7 +2560,7 @@ following (nearly) deterministic scheme.

  1. Convert the phrase to plain ASCII and remove any apostrophes. For example, -Müller's algorithm might become Muellers algorithm.
  2. +Müller's algorithm might become Muellers algorithm.
  3. Divide this result into words, splitting on spaces and any remaining punctuation (typically hyphens).
      @@ -2573,8 +2573,8 @@ recommendation does not apply.
    1. Now lowercase everything (including acronyms), then uppercase only the first character of:
        -
      1. … each word, to yield UpperCamelCase, or
      2. -
      3. … each word except the first, to yield lowerCamelCase
      4. +
      5. … each word, to yield UpperCamelCase, or
      6. +
      7. … each word except the first, to yield lowerCamelCase
    2. Finally, join all the words into a single identifier.
    @@ -2643,7 +2643,7 @@ and checkNonEmpty are likewise both correct.

    * wrapped normally. * @param {number} arg A number to do something to. */ -function doSomething(arg) { … } +function doSomething(arg) { … }

    or in this single-line example:

    @@ -2852,7 +2852,7 @@ documented when necessary. Return type may be omitted if the function has no non-empty return statements.

    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.

    +they are obvious from the rest of the method’s JSDoc or from its signature.

    Method descriptions begin with a verb phrase that describes what the method does. This phrase is not an imperative sentence, but instead is written in the @@ -3239,7 +3239,7 @@ 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.

  4. 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 +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.
@@ -3321,7 +3321,7 @@ to determine who owns the test results.

/** @bug 1234567 */
 function testSomething() {
-  // …
+  // …
 }
 
 /**
@@ -3329,7 +3329,7 @@ function testSomething() {
  * @bug 1234569
  */
 function testTwoBugs() {
-  // …
+  // …
 }