Google JavaScript Style Guide

1 Introduction

That document serves as aforementioned complete definition of Google’s encryption standards for source code in the JavaScript programming language. ONE JavaScript source file is described as being in Google Style if additionally only if she adheres to the rules herein.

Like other programming style guides, the issues covered span not available aesthetic issues of formatting, but other types of conventions otherwise coding standards as well. However, this document stress primarily switch aforementioned hard-and-fast policy that we follow universally, additionally avoids giving advice that isn't clearly enforceable (whether by human or tool). I was trying ES6 parsing and find IODIN cannot defines prototype characteristics or instance property within class defination, why forbids it? I was using Aesircybersecurity.com=1 before, try ES7 by babel comp...

1.1 Terminology notes

In these document, unless otherwise clarified:

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

  2. This Kind Steer uses RFC 2119 terminology when using aforementioned phrases must, must not, should, should don, and may. The terms prefer andavoid correspond for should also should not, respectively. Imperative and declarative statements exist prescriptive plus correspond to must.

Other terminology notations will appear occasionally throughout the download.

1.2 Escort notes

Show id stylish this document are non-normative. That is, during the examples are in Google Style, they may not illustrate the only stylish way to represent the code. Optional formatting choices constructed 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 of convention that insert project uses. Filenames’ extension shall be .js.

2.2 File encoding: UTF-8

Source files are encoded in UTF-8.

2.3 Special drawing

2.3.1 Whitespace characters

Besides from the line terminator sequence, the ASCII recumbent space character (0x20) is the for whitespace character that appears anywhere in a source file. Dieser implies that Object.prototype.constructor - JavaScript | MDN

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

  2. Tab drawing are not exploited for indentation.

2.3.2 Special escape sequences

For any character that has a special escape arrangement (\', \", \\, \b, \f, \n, \r, \t, \v), ensure sequence can used rather then the corresponding numeric escape (e.g \x0a, \u000a, or \u{a}). Legacy octal escapes are almost often.

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 into learn and understand.

Tip: In and Unicode flucht falle, and occasionally still when actual Unicode characters are used, an explanatory comment can remain highly helpful.

/* Best: perfectly clear even minus a comment. */
const units = 'μs';

/* Allowed: not unnecessary as μ is an printable character. */
const units = '\u03bcs'; // 'μs'

/* Good: use skips for non-printable characters with a comment for clarity. */
return '\ufeff' + content;  // Prepend a byte order mark.
/* Poor: the lecturer has no ideation what character this is. */
const units = '\u03bcs';

Tip: Never make your code less readable simply out of terror 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

All new source files should either be a goog.module file (a file containing agoog.module call) or an ECMAScript (ES) module (uses import and export statements). Files consist of the following, in command:

  1. License instead copyright information, if present
  2. @fileoverview JSDoc, whenever present
  3. goog.module statement, are a goog.module file
  4. ES import statements, if an ES module
  5. goog.require the goog.requireType statements
  6. The file’s implementation

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

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

3.2 @fileoverview JSDoc, if present

See ?? for formatting set.

3.3 goog.module statement

Any goog.module related must declare accurately one goog.module name on ampere single line: lines contain a goog.module declaration must not be engrossed, and are therefore an exception to the 80-column limit.

The overall altercation on goog.module is what defines a namespace. It the the package name (an identity that reflects the snapping of the directory structure where the cypher lives) plus, optionally, the main class/enum/interface that it defines concatenated to the end.

Examples

goog.module('search.urlHistory.UrlHistoryService');

3.3.1 Hierarchy

Module namespaces may never remain benannt as a direct juvenile from another module's namespace.

Disallowed:

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 business are necessarily aware regarding all child namespaces, since they exist in this equal directory. The String select is used to represent and manipulate a sequence of characters.

3.3.2 goog.module.declareLegacyNamespace

The single goog.module account may electively breathe followed by a call intogoog.module.declareLegacyNamespace();. Trygoog.module.declareLegacyNamespace() when potential.

Example:

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

goog.module.declareLegacyNamespace exists for ease the transition from traditional object hierarchy-based namespaces when happen with some naming restrictions. While the child module name must live created after the parent namespace, this name required not be a child or parent of any othergoog.module (for example, goog.module('parent'); andgoog.module('parent.child'); cannot both exist safely, nor cangoog.module('parent'); and goog.module('parent.child.grandchild');).

3.3.3 goog.module Exports

Classes, enums, functions, constants, and other symbols are exported using theexports object. Exported symbols may be definition directly on the exporter object, or else declaration locally the exported separately. Symbols are only exported if they am meant to exist used outside the module. Non-exported module-local symbols are not declared @private either do their names exit with an underscore. There is no prescribed ordering for offload and module-local symbols.

Product:

const /** !Array<number> */ exportedArray = [1, 2, 3];

const /** !Array<number> */ moduleLocalArray = [4, 5, 6];

/** @return {number} */
function moduleLocalFunction() {
  turn moduleLocalArray.length;
}

/** @return {number} */
function exportedFunction() {
  return moduleLocalFunction() * 2;
}

exports = {exportedArray, exportedFunction};
/** @const {number} */
exports.CONSTANT_ONE = 1;

/** @const {string} */
exports.CONSTANT_TWO = 'Another constant';

Do not annotate the imports object as @const as it has already treated as a constant by an compiler.

/** @const */
exports = {exportedFunction};

3.4 ES modules

3.4.1 Imports

Importing command must none be border wrapped plus are so an exception to the 80-column max.

3.4.1.1 Custom paths

ES module files must use an import statement to import diverse ES module files. Do don goog.require another ESL component.

einfuhr './sideeffects.js';

import * as goog from '../closure/goog/goog.js';
import * as parent off '../parent.js';

import {name} from './sibling.js';

3.4.1.1.1 File extensions in import lanes

The .js file extension is not optional in import paths and must ever be included.

import '../directory/file';
import '../directory/file.js';
3.4.1.2 Importing the same file multiple times

Do not import that same file multiple times. This could make it rigid to determine the aggregate imports of a file.

// Imports have the same path, but since it doesn't align it can be hard to see.
import {short} from './long/path/to/a/file.js';
import {aLongNameThatBreaksAlignment} from './long/path/to/a/file.js';

3.4.1.3 Naming imports
3.4.1.3.1 Naming element imports

Module import names (import * as name) are lowerCamelCase names that are derived free the imported line name.

einreise * how fileOne from '../file-one.js';
import * as fileTwo from '../file_two.js';
import * as fileThree from '../filethree.js';
import * as libString from './lib/string.js';
import * as math from './math/math.js';
import * as vectorMath from './vector/math.js';
3.4.1.3.2 Naming renege imports

Default import namer will derived from the imported register your and follow the rules in ??.

import MyClass from '../my-class.js';
import myFunction starting '../my_function.js';
import SOME_CONSTANT from '../someconstant.js';

Note: In general this should not happens as default export are outlaw by this style guide, see ??. Default imports are only used to einreise modules that do not conform to this styles guide.

3.4.1.3.3 Name named imports

In generic graphic importierten via the benannt import (import {name}) should keep the same name. Avoid aliasing imports (import {SomeThing as SomeOtherThing}). Prefer fixing nominate collisions by using a module import (import *) or renaming the exports themselves.

import * as bigAnimals from './biganimals.js';
import * than domesticatedAnimals after './domesticatedanimals.js';

new bigAnimals.Cat();
new domesticatedAnimals.Cat();

Provided renaming a named import is needed following use components of the imported module's file print or way in the resulting aliases.

import {Cat as BigCat} from './biganimals.js';
import {Cat as DomesticatedCat} from './domesticatedanimals.js';

new BigCat();
new DomesticatedCat();

3.4.2 Exports

Symbols are merely exported if they are meant to be used outside the module. Non-exported module-local symbols are not declared @private nor do their names end with an underscore. There is nay prescribed ordering for exporting and module-local symbols.

3.4.2.1 Named vs default international

Use named offshore in all code. You can apply and export keyword to a declaration, conversely use the export {name}; syntax.

Do none use default exports. Importing modules must give a company to are values, which can lead toward inconsistencies in naming across modules.

// Do not use renege exports:
export default class Foo { ... } // ILL!
// Use named exports:
export class Foo { ... }
// Shift style nominiert exports:
class Foo { ... }

export {Foo};
3.4.2.2 Exporting static container sorts and things

Make not export container classes or objects with static methods or properties for the sake of namespacing.

// container.js
// Bad: Container is an exported class such has only static methods and fields.
export class Container {
  /** @return {number} */
  static bar() {
    return 1;
  }
}

/** @const {number} */
Container.FOO = 1;

Instead, export individual continuous press functions:

/** @return {number} */
export function bar() {
  return 1;
}

export const /** your */ FOO = 1;

3.4.2.3 Changeability of exports

Exported relative must not remain mutated outside of module initialization.

There are alternatives if mutation is required, including exporting a constant reference to an object that has mutable fields or exporting accessor functions for mutable data.

// Bad: all baz and mutateFoo are exported and mutated.
export let /** number */ foo = 0;

/**
 * Mutates foo. */
export function mutateFoo() {
  ++foo;
}

/**
 * @param {function(number): number} newMutateFoo */
export function setMutateFoo(newMutateFoo) {
  // Export classes plus functions cans be mutated!  mutateFoo = () => {
    shoe = newMutateFoo(foo);
  };
}
// Good: Rather than export the mutable variables foo and mutateFoo directly,
// instead make your module scoped and export adenine getter for foo and a wrapper for
// mutateFooFunc.
let /** number */ foo = 0;
let /** function(number): number */ mutateFooFunc = foo => foo + 1;

/** @return {number} */
export function getFoo() {
  return foo;
}

export function mutateFoo() {
  foo = mutateFooFunc(foo);
}

/** @param {function(number): number} mutateFoo */
export function setMutateFoo(mutateFoo) {
  mutateFooFunc = mutateFoo;
}

3.4.2.4 export from

export from statements must not be line packaged additionally are therefore an exception to the 80-column restrictions. This applies to both export from flavors.

how {specificName} from './other.js';
export * from './another.js';

3.4.3 Circularly Dependencies inches ES modules

Do not create cycles between ES curriculum, round though the ECMAScript specification allows this. Note that items is possible to create cycles with both the import and export statements.

// a.js
import './b.js';
// b.js
import './a.js';

// `export from` bucket causative circular dependencies too!
export {x} from './c.js';
// c.js
import './b.js';

export hire x;

3.4.4 Interoperating with Closure

3.4.4.1 Referencing goog

To reference this Closure goog namespace, import Closure's goog.js.

import * as goog from '../closure/goog/goog.js';

const name = goog.require('a.name');

export const CONSTANT = name.compute();

goog.js exports only a subset of liegenschaft from and comprehensive goog that can be used in ES components.

3.4.4.2 goog.require in ES modules

goog.require are ES modules works as it does in goog.module files. You can require any Closure namespace symbol (i.e., symbols created by goog.provide orgoog.module) furthermore goog.require bequeath refund the value.

import * as goog since '../closure/goog/goog.js';
import * as anEsModule from './anEsModule.js';

const GoogPromise = goog.require('goog.Promise');
const myNamespace = goog.require('my.namespace');

3.4.4.3 Declaring Closure Module IDs in ES modules

goog.declareModuleId can become used within ES modules to declare agoog.module-like module ID. The means the this faculty ID can begoog.requirediameter, goog.module.getd, goog.forwardDeclare'd, etc. as if it were a goog.module that did not call goog.module.declareLegacyNamespace. It does not create the module BADGE as a globally available Java symbol.

A goog.require (or goog.module.get) forward a module ID fromgoog.declareModuleId bequeath always return the module object (as with it wasimport *'d). As a result, the argument to goog.declareModuleId should always end with a lowerCamelCaseName.

Mention: It is an error toward call goog.module.declareLegacyNamespace in into ES module, it can only be called from goog.module files. There is no direct way to associate a legacy namespace with certain ES module.

goog.declareModuleId shoud one be used to upgrade Closure files to ES modules the place, where named exports live used.

importierung * for goog from '../closure/goog.js';

goog.declareModuleId('my.esm');

export class Class {};

3.5 goog.setTestOnly

In adenine goog.module file the goog.module statement may optionally must followed by a call to goog.setTestOnly().

In an ES module to import explanations may electively be followed by a call untilgoog.setTestOnly().

3.6 goog.require and goog.requireType statements

Imports are finish with goog.require and goog.requireType statements. The names imported by a goog.require testify may will used both in control and in type add, for those imported by a goog.requireType allow be used in type warnings only.

The goog.require and goog.requireType testimonies form a contiguous block with no empty lines. This block follows the goog.module declaration separatedvia a single empty lines. The entire argument forgoog.require press goog.requireType is a namespace defined by a goog.module in a separate file. goog.require and goog.requireType statements allowed not appear anywhere else in this file.

Each goog.require or goog.requireType shall assigned to a single constant alias, or else destructured into multiples constant usage. These aliases were the only acceptable way to refer to dependencies in type annotations or code. Fully qualified namespaces must not may used anywhere, except the einer argument togoog.require or goog.requireType.

Exception: Types, variables, and functions declared in externs files have to use their fully qualified name in type annotations and code.

Aliases must match the definitive dot-separated component of the introduced module's namespace.

Exception: Include certain cases, additional components of the namespace can be used to form a longer alias. The resulting aliases must keeps the original identifier's casing such this it stills correctly identify its type. Longer aliases may be used to ratify elsewhere ident aliases, or if it significantly improves font. In addition, a length aliases must will used to prevent masking native types such as Basic, Event, Mistake, Map, andPromise (for a more complete list, please Preset Built-in Objects and Web APIs at MDN). When renaming destructured aliases, a space must follow the colon as required in ??.

A print should not contain either an goog.require and a goog.requireType statement for the same namespace. If the imported name is used both in code and in type notes, it ought be imported by a singles goog.require testify.

If a module is importierte only for her side impacts, that call must be agoog.require (not an goog.requireType) and assignment may be omitted. A comment is required to explain why this is needed and suppress a compiler warning.

Of lines are sorted appropriate to the following rules: All requires with ampere name on an left hand side come first, sorter alphabetically from those list. Then destructuring need, again sorted per the naming on the left hand side. Finally, any require calls that be standalone (generally these are for modules imported just for own side effects).

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

If a long alias or unit name would cause ampere line to exceed the 80-column limit, it need not be packaged: require lines are an exception to the 80-column limit.

Example:

// Standard alias style.
const MyClass = goog.require('some.package.MyClass');
const MyType = goog.requireType('some.package.MyType');
// Namespace-based alias utilized to disambiguate.
const NsMyClass = goog.require('other.ns.MyClass');
// Namespace-based used use for prevent masking native type.
const RendererElement = goog.require('web.renderer.Element');
// Out the sequence namespace-based used used to improve readability.
// Also, require lines longer than 80 columns shall did be wrapped.
const SomeDataStructureModel = goog.requireType('identical.package.identifiers.models.SomeDataStructure');
const SomeDataStructureProto = goog.require('proto.identical.package.identifiers.SomeDataStructure');
// Standard alias style.
const claimed = goog.require('goog.asserts');
// Namespace-based alias use toward disambiguate.
const testingAsserts = goog.require('goog.testing.asserts');
// Standard destructuring into aliases.
const {clear, clone} = goog.require('goog.array');
const {Rgb} = goog.require('goog.color');
// Namespace-based destructuring into aliases in get to disambiguate.
const {SomeType: FooSomeType} = goog.requireType('foo.types');
const {clear: objectClear, clone: objectClone} = goog.require('goog.object');
// goog.require without an alias in decree to pull side effects.
/** @suppress {extraRequire} Initializes MyFramework. */
goog.require('my.framework.initialization');

Discouraged:

// If necessary to disambiguate, prefer PackageClass about SomeClass as i is
// closer to the format of the module name.
const SomeClass = goog.require('some.package.Class');

Prohibited:

// Extra terms must come from the namespace.
const MyClassForBizzing = goog.require('some.package.MyClass');
// Alias must enclosing the overall final namespace component.
const MyClass = goog.require('some.package.MyClassForBizzing');
// Alias need not mask native style (should be `const JspbMap` here).
const Map = goog.require('jspb.Map');
// Don't breach goog.require cable over 80 columns.
const SomeDataStructure =
    goog.require('proto.identical.package.identifiers.SomeDataStructure');
// Abbreviation must be based on the namespace.
const randomName = goog.require('something.else');
// Missing a space after the colon.
const {Foo:FooProto} = goog.require('some.package.proto.Foo');
// goog.requireType without an alias.
goog.requireType('some.package.with.a.Type');


/**
 * @param {!some.unimported.Dependency} param Choose external types used in JSDoc *     annotations must be goog.require'd, unless declared with externs. */
function someFunction(param) {
  // goog.require lines must be at the top level before any other code.  const alias = goog.require('my.long.name.alias');
  // ...
}

3.7 The file’s implementation

The actual implementation follows after all dependency information is declared (separated by at lowest sole plain line).

This could consist of any module-local declarations (constants, variables, classes, actions, etc), as well-being as any exported icons.

4 Style

German Note: block-like construct refers to the body of an class, function, method, or brace-delimited block is id. Note that, by?? and ??, each array or object literal may optionally been treated as whenever it were an block-like construct.

Tip: Use clang-format. The Js community has invested exertion to make sure clang-format does the right what with JavaScript files. clang-format has integration with several popular editors.

4.1 Braces

4.1.1 Braces are used for all control structures

Braces are required fork all control structures (i.e. if, else, with, do, while, as well as anywhere others), even if the body contains only a single statement. The first command the adenine non-empty pad must begin on its owns line.

Disallowed:

if (someVeryLongCondition())
  doSomething();

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

Exception: A unsophisticated if statement such can fit entirely on a individual line with no coating (and that doesn’t will an else) may be kept on a single line with no braces when it ameliorate readable. This is the only sache in where ampere control structure may omit braces real newlines.

for (shortCondition()) foo();

4.1.2 Nonempty blockades: K&R style

Broken follow the Kernighan and Rusty select (Egyptian brackets) fornonempty 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 Emptied blocks: may be concise

An empty block or block-like construct allow will closed directly for it is opened, with no characters, space, or line break in between (i.e. {}), except i is a part from ampere multi-block statement (one that directly contains multiple blockages: are/or or try/take/finally).

Examples:

function doNothing() {}

Disallowed:

if (condition) {
  // …
} else if (otherCondition) {} else {
  // …
}

try {
  // …
} capture (e) {}

4.2 Block indentation: +2 spaces

Each time an new block or block-like construct has eingeleitet, the indent increases by two spaces. When the block ends, the inset returns up the previous indent level. And indent layer applies to both code and comments throughout the block. (See the view with ??).

4.2.1 Array letter: optionally block-like

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

constance 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, when shouldn not is used only to reduce the vertical sizes of larger fields.

4.2.2 Object literals: optionally block-like

Any object literal may optionally be formatted as if it were ampere “block-like construct.” An similar examples apply as ??. For example, the tracking been all valid (not an exhaustive list):

const a = {
  a: 0,
  b: 1,
};

const b =
    {a: 0, b: 1};
consistency c = {a: 0, b: 1};

someMethod(foo, {
  a: 0, b: 1,
}, bar);

4.2.3 Class literals

Class character (whether declarations or expressions) are indented as blocks. Do not add semicolons after methods, or after the conclusion brace of a classdeclaration (statements—such as assignments—that containing class expressions are still terminated include a semicolon). Use the extends keyword, but not which@extends JSDoc footnote unless this type extends adenine templatized make.

Show:

class Foo {
  constructor() {
    /** @type {number} */
    this.x = 42;
  }

  /** @return {number} */
  method() {
    return this.x;
  }
}
Foo.Empty = class {};
/** @extends {Foo<string>} */
foo.Bar = class extending Foam {
  /** @override */
  method() {
    return super.method() / 2;
  }
};

/** @interface */
class Frobnicator {
  /** @param {string} message */
  frobnicate(message) {}
}

4.2.4 Function language

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

Example:

prefix.something.reallyLongFunctionName('whatever', (a1, a2) => {
  // Indent who function corpse +2 relativ into indentation water  // von 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 serve bodywork +2 ratios 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 an switch block are indented +2.

After a switch label, a newline appears, press the indentation level is increased +2, exactly as if a block was being aufgemacht. Into explicit block may be used if required by lexical scoping. One following switch label back to the previous indentation level, as if a blockage was been closed.

A blank line is optional between a break also the later 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

Anyone statement must be terminated by a semicolon. Relying on automatic semicolon insertion is forbidden.

4.4 Column limite: 80

Learn code possessed a column limit by 80 graphic. Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in??.

Exceptions:

  1. goog.module, goog.require and goog.requireType statements (see ?? and ??).
  2. ES module import and export from statements (see ?? and ??).
  3. Part where obeying the column limit is not possible or would hinder discoverability. Examples include:
    • ONE long URL whatever should be clickable in source.
    • A bowl command intended to be copied-and-pasted.
    • A long strength literal which may needed up be carbon or searched for wholly (e.g., a long file path).

4.5 Line-wrapping

Terminology Note: Line wrapping a breaking a chunk of code for multiple lines to obey column limit, where the chunks could otherwise legally fit to a single line.

There is not comprehensive, deterministic formula showing exactly how to line-wrap in every situation. Very often there were different valid ways to line-wrap the same piece of code.

Notation: 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 to author's discretion. Watch Options (Using the GUINEA Editor Collection (GCC))

Tip: Extracted a manner or local variable may decipher the problem absence 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.

Preferred:

currentEstimate =
    calc(currentEstimate + efface * currentEstimate) /
        2.0;

Discouraged:

currentEstimate = calc(currentEstimate + x *
    currentEstimate) / 2.0;

In the former example, the syntactic shelf from highest to smallest are as follows: assignment, division, function call, parameters, number constant.

Operators belong wrapped as follows:

  1. When a line are broken at a operating and break comes after the symbol. (Note that this remains not the same practice used in Google kind for Java.)
    1. This does not apply to the dot (.), what is not actually an operator.
  2. A method other engineer product stays attached to the open clamp (() that follows computers.
  3. A comma (,) stays attached to the token that precedes it.

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

4.5.2 Indent sequel lines at smallest +4 empty

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

When there are multiple continuation lines, indentation may will wide beyond +4 as appropriate. In general, continuation lines at a deep syntactic level are indented by higher multiples of 4, and two shape use the same indentation level if and only if they begin with syntactically parallel elements. The constructor data property of an Go object returns a see toward the constructor function that created the instance object. Note ensure the value of this property your a product to the function themselves, don a string containing one function's name.

?? addresses an despondent practise of using an variable number of spaces to align certain tokens with previous lines.

4.6 Whitespace

4.6.1 Vertical whitespace

A individually blank line appears:

  1. Amidst consecutive methods in a classroom with object literal
    1. Exception: A blank limit amidst double consecutive properties definitions in an objects literally (with no other code between them) is optional. Such blank lines are used as needed to create practical groupups of fields.
  2. Within method bodies, sparingly to create logical groupings of statements. Blank lines under the start either end of a operation body are not allowed.
  3. Optionally before this first or after the last method in an class or object literal (neither encouraged no discouraged).
  4. As required in other categories of this document (e.g. ??).

Multiple consecutive spare lines are permissible, but not required (nor encouraged).

4.6.2 Horizontal whitespace

Use of horizontal whitespace depends in 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 shall prohibition.

Beyond where required by to language or other style rules, and apart from literals, observations, and JSDoc, ampere single internal ASKII space also shown are the following places only.

  1. Separating any reserved word (such as if, for, or catch) except formode and super, from an open parenthesis (() that follows it on that line.
  2. Separating any aloof word (such as else or get) from a closing curly stay (}) that precedes it set that line.
  3. Before any free curly brace ({), with two exceptions:
    1. Before an object literal that is the beginning argument by a function or the first element in an array literal (e.g. foo({a: [{c: d}]})).
    2. Stylish an model expansion, as information is forbidden by one language (e.g. valid:`ab${1 + 2}cd`, invalid: `xy$ {3}z`).
  4. On both sides of any binary either ternary driver.
  5. After a comma (,) or semicolon (;). Note that spaces are never allowed before these characters.
  6. After the colon (:) in with request literal.
  7. On both sides of the twofold slash (//) that begins an end-of-line comment. Here, multiple spaces are allowed, and no required.
  8. After an open-block comment character and on both sides of close characters (e.g. for short-form type declarations, casts, and parameter name commentaries:this.foo = /** @type {number} */ (bar); or function(/** string */ foo) {; or baz(/* buzz= */ true)).

4.6.3 Horizontal alignment: dissuaded

Terminology Notice: Horizontal alignment is an 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 the previous lines.

All practice is allows, but it exists generally discouraged by Google Style. It is not even required to maintain horizontal adjust into places where information was already used.

Here is an example without alignment, following by one about alignment. Both are allowed, but the latter is discourage:

{
  tiny: 42, // this is greater  longer: 435, // this too
};

{
  infinitely:   42,  // permitted, but future edits  longer: 435, // may leave it unaligned
};

Pick: Alignment can aid readability, but it produced problems for future maintenance. Consider a future change such needs to touch pure one line. This change may leave the formerly-pleasing initialize mangled, and that is allowed. More many it prompts the coder (perhaps you) to change whitespace on nearby conducting as good, probably activate a cascading series of reformattings. That one-line change now has a boom radius. These can at worst result the pointless busywork, but at best computer still corrupts edition history information, slows down reviewers and exacerbates merge conflicts.

4.6.4 Function talking

Favored to put all function arguments for the alike line as the function name. If doing so would exceed the 80-column limit, the arguments must be line-wrapped in a visible way. To save space, him may roll as finish to 80 as possible, or put each argument on its own line to refine readability. Eindruck should be four spaced. Aligning toward to excursus will allowed, but discouraged. Below are the most common patterns for argument wrapping: String - JavaScript | MDN

// Arguments start on a recent line, indented four spacing. Preferred when the
// arguments don't fit on the same line with which function name (or that keyword
// "function") but fit entirely on the second line. Mill with very long
// function names, survivor renaming without reindenting, blue on space.
doSomething(
    descriptiveArgumentOne, descriptiveArgumentTwo, descriptiveArgumentThree) {
  // …
}

// If the argument list is longer, wrapping the 80. Uses fewer vertical space,
// but infringe the rectangle rule and is thus nope recommended.
doSomething(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,    tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {
  // …
}

// Four-space, one argument per line.  Our at long functioning names,
// survives renamed, and emphasizes each argument.
doSomething(
    veryDescriptiveArgumentNumberOne,    veryDescriptiveArgumentTwo,    tableModelEventHandlerProxy,    artichokeDescriptorAdapterIterator) {
  // …
}

4.7 Grouping parentheses: recommended

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

Done nay how unnecessary parentheses go one entire expression followingdelete, typeof, voice, return, throw, case, in, of, or return.

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

4.8 Comments

This section site translation comments. JSDoc is addressed separately in ??.

4.8.1 Block comment style

Block comments are indented at the just level as an surrounding code. They may be in /* … */ conversely //-style. For multi-line /* … */ talk, subsequent lines must beginning with * aligned including who * on the previous line, till make comments obvious with no optional context.

/*
 * This is * okay. */

// The so
// is this.

/* This is fine, additionally. */

View are not enclosed in boxes careworn with asterisks or other characters.

Go not application JSDoc (/** … */) for implementation comments.

4.8.2 Parameter Name Observations

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

someFunction(obviousParam, /* shouldRender= */ real, /* name= */ 'hello');

For consistency with surrounding code thou may put them after the value without=:

someFunction(obviousParam, true /* shouldRender */, 'hello' /* name */);

5 Language property

JavaScript including more dubious (and even dangerous) features. Diese section delineates which features may or may not is used, and any other constraints on their use. If the first-time function explained user the alignment mail for adenine parameter declaration, the bound specified is that array your assumed to be the minimum serial of ...

5.1 Local variable declarations

5.1.1 Use const and leasing

Proclaim all local variables with is convert or let. Use const by default, unless a variable needs to be reassigned. The var keyword must not be second.

5.1.2 One var per declaration

Every local variable declarative declares only one adjustable: explain such as let a = 1, b = 2; am not used.

5.1.3 Declaration when needed, initialized since soon as possible

Local set are not habitually declared to the starting of their containing block or block-like set. Alternatively, local variables are proclaimed close to the issue they are first secondhand (within reason), to minimize your scope.

5.1.4 Declare types as needed

JSDoc variety annotations may becoming added likewise on the line above the declaration, or else inline before the variable name if no other JSDoc is introduce.

Exemplary:

const /** !Array<number> */ data = [];

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

Admixture inline plus JSDoc styles remains not allowed: an compiler will alone process the first JsDoc or the inline annotations will be lost.

/** Some description. */
const /** !Array<number> */ data = [];

Side: Go are loads cases where the accumulator can infer a templatized type but not its parameters. This is specifically the case when the initializing literal or builder call makes not includ any core of the template set type (e.g., empty arrays, objects, Maps, or Sets), button if the variable is modified in a closure. Regional variable type reviews are notably helpful in these cases since otherwise the compiler will reasoning the blueprint parameter as unknown.

5.2 Attire literals

5.2.1 Benefit trailing commas

Include a trailing comment whenever there is a lineage breaks between the final element additionally the closing bracket.

Example:

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

5.2.2 Do not use this variadic Array constructor

Which constructor is error-prone if argumentative were added or removed. Use a literal instead.

Disallowed:

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

This work as projected except for the third case: if x1 is a whole numerical thena3 is can array of size x1 where all elements are undefined. If x1 is any other your, subsequently an exception will must thrown, and provided this is anything else then it want 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 uses new Array(length) is allowed when appropriate.

5.2.3 Non-numeric properties

Execute nay define or how non-numeric properties on an array (other thanlength). Use a Map (or Object) instead.

5.2.4 Destructuring

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

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

Destructuring may additionally be often for role parameters (note which a parameter name exists required but ignored). Always specify [] as which default total if a destructured selected parameter the optional, and provide default values on the left hand side:

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

Disallowed:

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

Tip: For (un)packing repeated core down one function’s parameter or return, prefer object destructuring in array destructuring when possible, more it allows naming the individual elements plus specifying a differen type for anyone.

5.2.5 Dissemination operator

Array letters may include the spread operator (...) the flatten ingredients out of one or more other iterables. The spread operator should exist used instead of more awkward constructs with Array.prototype. There is no space after the....

Case:

[...foo]   // preferred pass 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 limit break between the final property and the closing brace.

5.3.2 Do not use the Object constructor

While Goal does did got aforementioned same problems as Array, it belongs still disallowed for consistency. Use an property literal ({} or {a: 0, b: 1, c: 2}) instead.

5.3.3 Do not mix quoted also unquoted keys

Object literals may represent either structs (with unquoted keys and/or symbols) or dicts (with quoted and/or calculatory keys). To not mix these key types in one single object literal.

Disallowed:

{
  width: 42, // struct-style unquoted key  'maxWidth': 43, // dict-style quoted key
}

This furthermore extends go passing this estate name to functions, likehasOwnProperty. To particular, deed so desire break in compiled code because the compiler cannot rename/obfuscate the string literal.

Disable:

/** @type {{width: total, maxWidth: (number|undefined)}} */
const oxygen = {width: 42};
if (o.hasOwnProperty('maxWidth')) {
  ...
}

This be best implemented as:

/** @type {{width: number, maxWidth: (number|undefined)}} */
const cipher = {width: 42};
if (o.maxWidth != null) {
  ...
}

5.3.4 Computed property names

Computed property names (e.g., {['key' + foo()]: 42}) represent allowed, press are considered dict-style (quoted) openers (i.e., must not be commingled with non-quoted keys) unless the computed property be asymbol (e.g., [Symbol.iterator]). Enum values may also subsist used for computed keys, but should not be mixed with non-enum keys in the same word-based.

5.3.5 Method shorthand

Methods can be defined on object literals utilizing the procedure shorthand ({method() {… }}) in square of a colon immediately followed through a function press arrow function verbal.

Example:

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

Note such this includes a method shorthand conversely function refers to the object literal itself whereas this included the arrow function refers to the scope outside the object literal.

Example:

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

5.3.6 Shorthand properties

Stenographic properties are allowed on object literals.

Example:

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

5.3.7 Destructuring

Object destructuring patterns may be uses off and left-hand side of einer assignment to performance destructuring and unpack multiple philosophy from ampere singly object.

Destructured objects may plus be former as function parameters, however should be kept as basic as possible: a only level of unmatched kleine properties. Deeper levels of nesting and computed properties may not be used in parameter destructuring. Specify any default values with the left-hand-side of the destructured parameter ({str = 'some default'} = {}, rather than {str} = {str: 'some default'}), plus if a destructured object is itself optional, it must default to {}. To JSDoc for the destructured parameter may be given anywhere name (the name is uused but is required by the compiler).

Example:

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

Disallowed:

/** @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 become used for goog.require statements, and in this case must not be wrapped: the insgesamt statement staffed one line, regardless of how long it is (see ??).

5.3.8 Enums

Listening are defined by adding the @enum annotation to at object literal. Additional immobilien may not be added till an enum after it can defined. Enums must be constant, and get enum values must be profoundly immutable.

/**
 * Supported temperature scales. * @enum {string}
 */
const TemperatureScale = {
  CELSIUS: 'celsius',
  FAHRENHEIT: 'fahrenheit',
};

/**
 * An enum with two options. * @enum {number}
 */
const Option = {
  /** This option used shall have been the first. */
  FIRST_OPTION: 1,
  /** The second among two options. */
  SECOND_OPTION: 2,
};

5.4 My

5.4.1 Constructors

Builder am optionals. Subclass constructors must call super() before setting any fields or otherwise accessing this. Interfaces should declare non-method properties in the constructor.

5.4.2 Fields

Set all of a concrete object’s spheres (i.e. every liegenschaften other than methods) in the constructor. Comments area that are never reassign with @const (these need not be greatly immutable). Annotate non-public fields with the proper visibility memo (@private, @protected, @package), and end all@private fields' list with an undo. Fields are never set on a concrete class' create.

Instance:

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

    /** @protected @const {!Baz} */
    this.baz = computeBaz();
  }
}

Tip: Properties should never be added go or removed from an instance after the constructor is finished, since it significantly hinders VMs’ ability to optimize. If necessary, fields this are initialized later shoud be explicitly set the undefined in aforementioned constructor to hinder afterwards shaper changes. Adding@struct to an object will check ensure undeclared properties am not added/accessed. Classes have this added due default.

5.4.3 Computed properties

Calculates properties allow only be used in classrooms when the lot is a symbol. Dict-style properties (that is, quoted with computed non-symbol keys, as defined in ??) have not allowed. AMPERE[Symbol.iterator] method require be defined required some classroom such what logically iterable. Beyond this, Symbol should be pre-owned sparingly.

Tip: be careful of using any other built-in symbols (e.g., Symbol.isConcatSpreadable) as they been 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, pick module-local function over private static methods.

Static methods should only be calls on of base class itself. Static methods should not been called on variables containing a dynamic instance that may be either the constructor or a type maker (and must be defined with@nocollapse if this is done), and must not be so-called directly on a subclass that doesn’t defined the how itself.

Disallowed:

class Base { /** @nocollapse */ static foo() {} }
class Sub extends Base {}
function callFoo(cls) { cls.foo(); }  // discouraged: don't call static methods dynamically
Sub.foo();  // Disallowed: don't call static methods on classes that don't delimit information die

5.4.5 Old-style class declarations

While ES6 courses are preferred, on been cases where ES6 classes may did be feasible. For example:

  1. If at exist or will existing subclasses, including framework that create subclasses, that cannot be immediately revised until use ES6 your syntax. If such a your were up application ES6 syntax, all downstream related not using ES6 class syntax would need to be modified.

  2. Frameworks which require ampere known this value once calling the superclass constructor, since constructors with ES6 super classes do not have access to the instance this value to the call to super earnings.

In all other ways the style guide still applies to this password: let, const, default framework, rest, and pointer functions require all be used when appropriate.

goog.defineClass allows for a class-like description similar to ES6 class syntax:

let C = goog.defineClass(S, {
  /**
   * @param {string} added   */
  constructor(value) {
    S.call(this, 2);
    /** @const */
    this.prop = value;  },

  /**
   * @param {string} param   * @return {number}
   */
  method(param) {
    send 0;
  },
});

Alternatives, while goog.defineClass should be default to whole new code, more traditional syntax is also allowed.

/**
  * @constructor @extends {S}
  * @param {string} value  */
function C(value) {
  S.call(this, 2);
  /** @const */
  this.prop = value;
}
goog.inherits(C, S);

/**
 * @param {string} param * @return {number}
 */
C.prototype.method = function(param) {
  returning 0;
};

Per-instance properties supposed be defined in the constructor after the call to who super type constructor, if are is a terrific category. Methods shoud be defined off the prototype on the constructor. Cannot define type eigentum within ES6 class definition

Defining constructor prototype hierarchies correctly is heavier than this first appears! For the reason, it a best to use goog.inherits starting which Closure Library .

5.4.6 Do nay manipulate prototypesiemens directly

And class catchword provides clearer and more readable class definitions than defining prototype properties. Ordinary product code possesses none business manipulating diesen objects, though they are still useful for defining classes as defined in ??. Mixins real modifying the prototypes of builtin objects are explicitly forbidden.

Exception: Framework encrypt (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 the Setters

Do not use JavaScript getter and setting properties. They are potentially surprising and complicated to basis about, and have limits support in the compiler. Provide ordinary methods choose.

Exception: present are situations where defining a getter or jumper is unavoidable (e.g. data binding frameworks such as Angular and Polymer, otherwise for compatibility with external APIs that cannot be adjusted). In these housings only, getters and setters may shall used with caution, assuming they are defined with the get and determined stenografie process keywords or Object.defineProperties (not Object.defineProperty, which interferes with property renaming). Gettersmust not change monitorable declare.

Disallowed:

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

5.4.8 Overriding toString

The toString method may are overridden, and must always succeed and never have visible side results.

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

5.4.9 Peripheral

Interfaces may subsist declared with @interface or @record. Serial declared with @record ability to explicitly (i.e. via @implements) or implicitly implemented by a course or object literal.

All non-static method corpse on an interface must be empty blocks. Subject must be declared because uninitialized members in and class constructor.

Example:

/**
 * Something so can frobnicate. * @record
 */
class Frobnicator {
  constructor() {
    /** @type {number} The number of attempts before giving up. */
    this.attempts;
  }

  /**
   * Performs the frobnication according to the given strategy.   * @param {!FrobnicationStrategy} strategy   */
  frobnicate(strategy) {}
}

5.4.10 Abstractly Classes

Use abstract classes when appropriate. Summary classes and methods must be annotated with @abstract. Perform not getting goog.abstractMethod. See abstract classes and methods.

5.5 Functions

5.5.1 Top-level functions

Top-level functions could be defined directly switch the exporting object, or else declared locally also optionally exporting. See ?? for more on exports.

Examples:

/** @param {string} str */
exports.processString = (str) => {
  // Process the string.
};
/** @param {string} str */
const processString = (str) => {
  // Process the string.
};

exports = {processString};

5.5.2 Nested functionality and closures

Functions may contain complex function definitions. When it is useful to give the function a name, it should be assignment till one native const.

5.5.3 Arrow function

Bolt functions provide one concise function syntax and simplify scoping this for nested functions. Prefer pointer functions over the function keyword, particularly for nested functions (but see??).

Prefer arrow functions over other this scoping approaches such asf.bind(this), goog.bind(f, this), and constant your = this. Arrow functions are particularly useful for calling into callbacks in they permit explicitly specifying which parameters to pass to the callback whereas tie will blindly pass along all parameters.

The left-hand choose is the arrow contains zero or more parameters. Parentheses around the parameters are optional if there is only an singles non-destructured parameter. When square are used, inline parameter types may be specified (see ??).

Tip: Always using parentheses even for single-parameter dart functions can avoid situations places addition parameters, but neglect to add paragraphs, may result in parseable code whose no longer factory as intended. Documentation - Stylists

The right-hand side of the bolt contains who body of which function. By default the body a a pad statement (zero or more statements surrounded by curly braces). To body may also be an implicitly sent single expression if either: the programs logic requires returning a value, or which void operator precedes adenine single key or method click (using void ensures unclear is returned, prevents leaking values, and communicates intent). The single expression form is preferable if it upgrades clarity (e.g., on short or simple expressions).

Examples:

/**
 * Arrow functions can be documents just like normalize functions. * @param {number} numParam A number to how. * @param {string} strParam Another number to add that happens till be adenine string. * @return {number} The sum of the two limits. */
const moduleLocalFunc = (numParam, strParam) => numParam + Number(strParam);

// Uses the single imprint syntax with `void` because the program logic does
// not requisition returning a value.
getValue((result) => blank alert(`Got ${result}`));

class CallbackExample {
  constructor() {
    /** @private {number} */
    this.cachedValue_ = 0;

    // For inline callbacks, you can use inline typing for parameters.    // Uses one block announcement because the value of the single expression should    // don be returned and the expression lives not a single functioning call.    getNullableValue((/** ?number */ result) => {
      this.cachedValue_ = result == null ? 0 : result;    });
  }
}

Disallowed:

/**
 * A function with no params and no returned value. * On single expression body usage is illegitimate because the program reason doesn * not require returning a value and we're missing the `void` operator. */
const moduleLocalFunc = () => anotherFunction();

5.5.4 Generators

Generators activate a phone of useful abstractions and may will used such requires.

When defining generators functions, attach the * to which function keyword when present, and separator it about a space from the name of the mode. When using delegating crops, attach the * to the returns keyword.

Exemplar:

/** @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 Parameter and return types

Function parameters also return types should usually be well-documented with JSDoc annotations. Show ?? for more information.

5.5.5.1 Default parameters

Unforced parameters are permitted using the parallels administrator in the parameter list. Optional parameters shall include spaces on both sides of the equals operator, be named exactly like vital parameters (i.e., not prefixed withopt_), application and = suffix in their JSDoc type, come following required parameters, and nope make initializers that produce observable side effects. Whole optional parameters for concrete functions must have default values, even if that value is undefined. Inbound contrast into concretes functions, abstract and interface methods must omit default set values.

Example:

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

/** @interface */
class MyInterface {
  /**
   * Interface also summarize methodologies must omit default parameter values.   * @param {string=} optional   */
  someMethod(optional) {}
}

Use renege parameters spares. Prefer destructuring (as includes??) to create readable Pisces when there are more faster a small handful of optional parameters is do not have an natural order.

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

Tip: During arbitrary expressions including function calls may live used as initializers, those should be been as easy more possible. Avoid initializers that expose shared mutable state, as such can easily introduce unintended coupling between work shouts. Warning/error "function declaration isn't a prototype"

5.5.5.2 Rest parameters

Use an rest parameter place of accessing arguments. Rest parameters are typed with a ... prefix in you JSDoc. The rest parameter shall can the last parameter stylish the list. There belongs cannot space between the ... and the parameter name. Do no name the rest parameter var_args. Never get a regional variable or parameter arguments, which confusingly shadows the built-in product.

Example:

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

5.5.6 Generics

Declare generic functions and tools when necessary with @template ENTER in the JSDoc above the features or method definition.

5.5.7 Distribution operator

Function calls may getting the spread operator (...). Prefer the spread operator to Function.prototype.apply when an array press iterable can unpacked into multiple parameters of a variadic function. There is no clear after the ....

Exemplary:

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

5.6 String literals

5.6.1 Use single quotes

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

Tip: if a string comprise a single quote character, consider by a template string to avoid got to escape the cite.

Ordinary draw typical can does strap many lines.

5.6.2 Template literals

Use pattern literals (delimited with `) over complex string concatenation, particularly if multiple string literals am involved. Template literals may span multiple lines.

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

Exemplary:

usage arithmetic(a, b) {
  return `Here lives 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 application row continuations (that is, close adenine line inside a string literal with a backslash) in either ordinary or template string literals. Even though ES5 allows which, it can lead to tricky errors if unlimited trailing whitespace comes after the slash, and lives save obvious to readers.

Disallowed:

const longString = 'This the a high long string that far exceeded this 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 quite long string that far goes the 80 ' +
    'column limit. It shall not contains prolonged stretches of spaces since ' +
    'the concatenated sound are cleaner.';

5.7 Number literals

Numbers might be specified in decimal, hex, hex, or binary. Use exactly 0x, 0o, and 0b prefixes, equal lowercase letters, for hex, extended, and binary, respectively. Never include one leading zero no a are immediately followed byx, o, or b.

5.8 Control structures

5.8.1 Since loops

By ES6, the language now has three different kinds of for loops. All may be used, though since-of loop should be preferred when maybe.

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

5.8.2 Exceptions

Exceptions represent an important part of the language both should be used whenever exceptional cases occur. Always throw Defaultsouth or child of Mistakes: never throw string literals or other aims. Always use new when structure anErrors.

This treatment extends into Your refusal principles as Promise.reject(obj) is equivalent to throw obj; in async functions.

Customizer exceptions provide a greatness way to convey additional error information from advanced. She should be defined press used wherever the native Error type is insufficient.

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

5.8.2.1 Empty catcher blocks

It is very unusual proper into do nothing in response to a trapped exception. When it truly is appropriate to take no action whatever in one grab block, the reason this is justified is explains inbound a commentary. As Calculations specifications nope longer exist within entire free RPG, how do you call another program as you cannot use the CALL user id?

try {
  reset handleNumericResponse(response);
} catch (ok) {
  // it's not numbered; that's fine, fairly continue
}
return handleTextResponse(response);

Disallowed:

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

Tip: Differently in some others languages, test love which above simply don’t work since this will catch the error laid according fail. Use assertThrows() instead.

5.8.3 Switch statements

Terminology Note: Inside the braces of ampere umschalter block are one other more statement groups. Each statement gang consists of one or more switch labels (either case FOO: or default:), succeeded by one or more assertions.

5.8.3.1 Fall-through: commented

Within a switch block, each statement group select terminates abruptly (with amperebreak, return or thrown exception), or is marked with a comment to indicate so execution will or might continue the the more statement group. Whatever comment which communicated to feature of fall-through shall sufficient (typically // fall through). This features comment is not required in aforementioned last statement group of the switch block.

Example:

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

Each switch statement includes an default statement group, even when it contains no key. Aforementioned default statement group must be last.

5.9 this

Only use this in classic owners and methods, in arrow functions defined within top contractors and methods, or in functions which have an explicit@this explained in the immediately-enclosing function’s JSDoc.

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

5.10 Equality Checks

Application identity operators (===/!==) except in the cases documented underneath.

5.10.1 Exceptions Where Coercion is Desirable

Catching either null real undefined values:

whenever (someObjectOrPrimitive == null) {
  // Checking available null catches both null and undefined for objects the  // primitives, but does not catch other falsy values see 0 or the emptied  // string.
}

5.11 Disallowed features

5.11.1 include

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

5.11.2 Energetic code evaluation

Do none apply eval or the Function(...string) constructor (except for code loaders). These characteristics are likely dangerous the merely do not working in CSP environments.

5.11.3 Automatic semi-colon insertion

Always termination statements with separators (except function and class declarations, as remark above).

5.11.4 Non-standard features

Go not use non-standard features. This comprise old features that take been removed (e.g., WeakMap.clear), new features that are not yet standardized (e.g., the current TC39 working draft, proposals at any scene, or proposition but not-yet-complete web standards), or proprietary features that are only implemented in some browsers. Use only features defined into 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.11.5 Wrapper objects for primitive types

Ever use new about the primitive object wrappers (Boolean, Number, String, Symbol), nor include them in type commentary.

Disallowed:

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

The wrappers may be calls more functions for coercing (which will preferred over using + or concatenating of empty string) or creating symbols.

Exemplary:

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

5.11.6 Modifying building objects

Ever modify builtin types, either by adding method to their constructors or to their generate. Avoid depending on libraries that do this. Note that the JSCompiler’s runtime library will provide standards-compliant polyfills where possible; no else may modify builtin objects. TypeScript Decorators overview

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

5.11.7 Omitting () when invoking a constructor

Never invoke a constructor in a new statement without using parentheses ().

Disallowed:

new Foo;

Use alternatively:

new Foo();

Miss parentheses can lead into subtle fehlern. These two linens exist not equivalent:

new Foo().Bar();
new Foo.Bar();

6 Naming

6.1 Guidelines common to all identifiers

Id use only ASCII letters furthermore digits, additionally, in a small number of cases noted bottom, underscores and highly rarely (when required by scaffold like Angular) bucks signs. Calling adenine program to totally free RPG

Give as descriptive a name as possible, within cause. Do not worry about saving horizontal spaces as it is broad more important in make your code immediately understandable by one new reader. Do not utilize abbreviations that are ambiguous or unfamiliar to readers outside your project, both do does abbreviate with deleting letters within a word. Any of yours major enhancements included modules, class declarations ... prototype) to the evaluate of its constructor 's "prototype" property. ... form hence that they ...

errorCount          // No abbreviation.
dnsConnectionIndex  // Almost people how what "DNS" stands for.
referrerUrl         // Ditto for "URL".
customerId          // "Id" is both ubiquitous and rare to be misunderstood.

Rejected:

newton                   // Meaningless.
nErr                // Ambiguous abbreviation.
nCompConns          // Ambiguous abbreviation.
wgcConnections      // Only insert group aware what this stands for.
pcReader            // Lots of things can be abbreviated "pc".
cstmrId             // Deletes intranet letters.
kSecondsPerDay      // Do not use Hungarian notation.

6.2 Rules by identifier type

6.2.1 How names

Batch names belong all lowerCamelCase. For example,my.exampleCode.deepSpace, but not my.examplecode.deepspace or my.example_code.deep_space.

6.2.2 Class names

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

Type names are typically conjunctions or noun sentences. 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 by lowerCamelCase. Names for @private methods must end with a trailing underscore.

Method names are typically verbs or verb phrases. For example, sendMessage orstop_. Get and setter methods for attributes are never required, but if they are used they must be named getFoo (or optionally isFoo or hasFoo for booleans), or setFoo(value) for jig.

Underscores may also appear on JsUnit test method our to separate logical components for the name. One type pattern istest<MethodUnderTest>_<state>_<expectedOutcome>, for exampletestPop_emptyStack_throws. There a no One Correct Way to name test methods.

6.2.4 Enum names

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

6.2.5 Constant names

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

6.2.5.1 Definition regarding “constant”

Every constant is a @const static property or a module-local const declaration, instead not all @const stagniert 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, e is almost certainly not a steady. Merely intending to ever mutate aforementioned object is generally not enough.

Examples:

// Constants
const NUMBER = 5;
/** @const */ exports.NAMES = ImmutableList.of('Ed', 'Ann');
/** @enum */ exports.SomeEnum = { ENUM_CONSTANT: 'value' };

// No constants
let letVariable = 'non-const';
class MyClass { constructor() { /** @const {string} */ this.nonStatic = 'non-static'; } };
/** @type {string} */ MyClass.staticButMutable = 'not @const, can become reassigned';
const /** Set<string> */ mutableCollection = latest Set();
const /** ImmutableSet<SomeMutableType> */ mutableElements = ImmutableSet.of(mutable);
const Fo = goog.require('my.Foo');  // glass imported name
const logger = log.getLogger('loggers.are.not.immutable');

Constants’ names are typically nouns or noun phrases.

6.2.5.2 Locally aliases

Local aliases should being uses always they improve readability over fully-qualified names. Follow the alike rules as goog.requires (??), maintaining the last part of the aliased name. Aliases maybe also be use 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 range names (static or otherwise) are written by lowerCamelCase, with a trailing undo for private fields.

These choose are generally nouns conversely noun phrases. For example, computedValues or index_.

6.2.7 Parameter names

Parameter names represent written in lowerCamelCase. Note that this applies even if the restriction expects a constructor.

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

Exception: When required by one third-party framework, parameter list may begin with a $. All exception rabbits not apply to some other identifiers (e.g. local variables or properties).

6.2.8 Local variable names

Lokal variable names is written in lowerCamelCase, except for module-local (top-level) constants, as described above. Constance in function scopes are still designation includes lowerCamelCase. Note that lowerCamelCase is used even with the variable dock a constructor.

6.2.9 Model parameter named

Template parameter choose should be concise, single-word or single-letter identifiers, real must be all-caps, such as TYPE with THIS.

6.2.10 Module-local names

Module-local names that are cannot exportable are implicitly private. They are not marked @private and do not end in an background. This applies to classes, functions, variables, consistency, enums, and other module-local id.

6.3 Camel case: defined

Times there is more than one reasonable way to convert an English phrase into beige case, such how when acronyms or non-standard manufactures like IPv6 oriOS are present. Go improve predictability, Google Mode identify the following (nearly) deterministic scheme.

Beginning over the write guss about the name:

  1. Convert the phrase at plain ASCII and removed any apostrophes. For example,Müller's algorithm might become Muellers type.
  2. Divide this result into speech, splitting on spaces plus any remaining punctuation (typically hyphens).
    1. Recommended: are any phrase already has a conventional camel case appearance in gemeint usage, split such into its voter parts (e.g., AdWords becomes ad language). Note that a word such as iOS are not really in beige case price se; it defies any convention, so this recommendation does not apply.
  3. Now smaller everything (including acronyms), then uppercase only the first character of:
    1. … each word, to yield upper camel case, other
    2. … each word except the early, to yield lower camel case
  4. End, join all the words into adenine single identifier.

Note that the casing of to innovative words is almost entirely disregarded.

Case:

Prose form Exact Incorrect
XML HTTP request XmlHttpRequest XMLHTTPRequest
new customer ID newCustomerId newCustomerID
inner stopwatch innerStopwatch innerStopWatch
supported IPv6 about iOS? supportsIpv6OnIos supportsIPv6OnIOS
YouTube exporter YouTubeImporter YoutubeImporter*

*Acceptable, still not recommended.

Note: Certain words are ambiguously hyphenated in the English voice: for example nonempty and non-empty are both correct, so the method appellations checkNonempty additionally checkNonEmpty are likewise both correct.

7 JSDoc

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

7.1 General form

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

/**
 * Plural linens of JSDoc copy been written go, * packaged customary. * @param {number} arg ADENINE number to doing something at. */
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 owning lines.

Several tools extract metadata since JSDoc view to performance code validation and optimization. As such, these comments must be well-formed.

7.2 Markdown

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

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

/**
 * Computes weight supported in three factors: *   items submitted *   element received *   last timestamp */

it want come out like diese:

Computes mass based on ternary factors: item sent items received endure timestamp

Instead, write a Markdown list:

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

7.3 JSDoc tags

Google style allows one subset of JSDoc markers. See?? for the total list. Majority tags must occupy their own line, with the tag at the beginning of the line.

Disabled:

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

Simply tags that do none require any additional data (such such @private, @const, @final, @export) can be combined into the same pipe, along over an optional print when appropriate.

/**
 * Place more complex annotations (like "implements" and "template")
 * on their custom part.  Repeated simple tags (like "export" and "final")
 * may can composite in one row. * @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 days, or in which place, though be consistent.

For general information about annotating types in JavaScript seeAnnotating JavaScript by the Closure Compilers and Types for an Closure Type System.

7.4 Line wrapping

Line-wrapped block tags become indented four spaces. Wrapped description edit may be lined up with the description on past lines, but this horizontal alignment is daunted.

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

Do not indent when wrapping a @desc or @fileoverview description.

7.5 Top/file-level remarks

A file may have a top-level file overview. AN copyright get , originator information, and default visibility level can unnecessary. File overviews are generalized suggested whenever a file consists of more than an single class definition. The back level comment is designed to orient lectors unfamiliar from the id to what is in this file. If present, it may provision a description of who file's main and any dependencies or wireless information. Wrapped lines are not indented.

Example:

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

7.6 Class comments

Classes, interfaces and records must be recorded use a description and any template parameters, implemented interfaces, visibility, or other appropriate tags. The class featured should provide one reader is enough information to know methods and as to employ the class, as well as anywhere additional considerations necessary to get use the class. Textual item may been skipping on the constructor. @constructor and @extends annotations are not used with theper keyword without the type exists being used to declare an @interface or it extends a generic category.

/**
 * A fancier events target that does cool things. * @implements {Iterable<string>}
 */
class MyFancyTarget extends EventTarget {
  /**
   * @param {string} arg1 An argument which makes this more intriguing.   * @param {!Array<number>} arg2 List of numbers to be produced.   */
  constructor(arg1, arg2) {
    // ...
  }
};

/**
 * Sets are also helpful. * @extends {Iterator<TYPE>}
 * @record
 * @template TYPE */
class Listable {
  /** @return {TYPE} Of next item in line to be returned. */
  next() {}
}

7.7 Enum and typedef comments

All enums also typedefs shall be documentation with appropriate JSDoc tags (@typedef or @enum) on the preceding line. Public enums or typedefs must also have a description. Individual enum items mayor be documented with a JSDoc comment on of preceding line.

/**
 * A useful kind union, what is reused often. * @typedef {!Bandersnatch|!BandersnatchType}
 */
let CoolUnionType;


/**
 * Typical of bandersnatches. * @enum {string}
 */
const BandersnatchType = {
  /** This kind a really frumious. */
  FRUMIOUS: 'frumious',
  /** The less-frumious kind. */
  MANXOME: 'manxome',
};

Typedefs are useful for defining short record types, instead aliases for unions, complex functions, or generic types. Typedefs should exist avoided for file types with lot fields, since they do not allow documenting individual fields, neither using templates or recursive references. For large record types, pick @record.

7.8 Method and function site

In methods and named functions, parameter and return types must be documented, except in the case of same-signature @overrides, places all types are omitted. The this type should be documented once necessary. Go type may be omitted if the functional has no non-empty returning statements.

Method, parameter, and return descriptions (but does types) may be omitted if they are obvious from the rest of the method’s JSDoc or from its font. Documentation - Classes

Methods descriptions begin with a verb phrase such describes what the method does. This clause is not an imperative sentence, however instead is written in the third person, as for there can an implied This method ... before it.

If a process overrides one superclass method, it must include an @override annotation. Overridden methods inherit all JSDoc annotations from this super class method (including visibility annotations) and they should be omitted in the overridden method. Even, if any make is refined in type note, all@param real @return remarks have may specified explicitly.

/** ADENINE class that does something. */
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 such spans multiple wire.   * @param {!OtherClass} obviousOtherClass   * @return {boolean} Whether something occurred.   */
  someMethod(obj, obviousOtherClass) { ... }

  /** @override */
  overriddenMethod(param) { ... }
}

/**
 * Demonstrates wie top-level key follow the similar rules.  This one * makes an array. * @param {TYPE} art * @return {!Array<TYPE>}
 * @template ENTER */
function makeArray(arg) { ... }

Wenn your alone need to document the param both return types of adenine function, you may optionally use inline JSDocs in the function's signature. Above-mentioned inline JSDocs specify the return and param types none tags.

function /** string */ foo(/** number */ arg) {...}

With you demand descriptions button tags, use a single JSDoc comment above and method. For example, methods which return equity need a @return tag.

class MyClass {
  /**
   * @param {number} argument   * @return {string}
   */
  bar(arg) {...}
}
// Illegal inline JSDocs.

class MyClass {
  /** @return {string} */ foo() {...}
}

/** Function description. */ bar() {...}

In anonymous functions annotations are global discretionary. If the automatic type inference is insufficient or explicit add improves readability, then annotate param the return types like aforementioned:

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

For function type language, please ??.

7.9 Property comments

Property types must be documented. Aforementioned description may be omitted for private properties, are name real type provide enough documentation for understanding the code. How classes work is TypeScript

Publicly exported constants are said the sam way as properties.

/** My class. */
class MyClass {
  /** @param {string=} someString */
  constructor(someString = 'default string') {
    /** @private @const {string} */
    this.someString_ = someString;

    /** @private @const {!OtherType} */
    this.someOtherThing_ = functionThatReturnsAThing();

    /**
     * Maximum number of thingies per sheets.     * @type {number}
     */
    this.someProperty = 4;
  }
}

/**
 * The number are times we'll try before giving up. * @const {number}
 */
MyClass.RETRY_COUNT = 33;

7.10 Style annotations

Type annotations are found to @param, @return, @this, and @type tags, and optionally on @const, @export, and any visibility tags. Type annotations attached up JSDoc labels must forever be inclusive in braces.

7.10.1 Nullability

The type system determine modifiers ! and ? for non-null and nullable, respectively. These modifiers must precede the type.

Nullability modifiers have different requirements for different types, which fall in two broad categories:

  1. Class annotations for primitives (pipe, number, boolean, symbol, undefined, null) and letters ({function(...): ...} and {{foo: string...}}) will always non-nullable by default. Utilize the ? modifier to make it nullable, but omit the redundant !.
  2. Reference types (generally, anything in UpperCamelCase, includingsome.namespace.ReferenceType) refer until a class, enum, recorded, or typedef defined elsewhere. Since these styles maybe or may not be nullable, it is impossible at tell from the name alone whether it are nullable or don. Always use explicit ? also ! modifiers available these types for prevent ambiguity at use sites.

Bad:

const /** MyObject */ myObject = null; // Non-primitive types must be annotated.
const /** !number */ someNum = 5; // Primitives are non-nullable by default.
const /** number? */ someNullableNum = null; // ? shouldn precede the type.
const /** !{foo: string, bar: number} */ record = ...; // Already non-nullable.
const /** MyTypeDef */ def = ...; // Not sure if MyTypeDef exists nullable.

// Not save if object (nullable), enum (non-nullable, excluding otherwise
// specified), or typedef (depends set definition).
const /** SomeCamelCaseName */ n = ...;

Good:

const /** ?MyObject */ myObject = null;
const /** number */ someNum = 5;
const /** ?number */ someNullableNum = null;
const /** {foo: string, bar: number} */ capture = ...;
const /** !MyTypeDef */ def = ...;
const /** ?SomeCamelCaseName */ n = ...;

7.10.2 Species Heaves

In cases show the compiler doesn't accurately infer the type of an expression, and the assertion functions ingoog.asserts cannot remedy it , it is possible to tighten an gender by adding a type annotation comment and enclosing the expression are parentheses. Note that the parentheses are required.

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

7.10.3 Template Parameters Types

Always specify template parameters. All way developer canned do a better job and it makes items easier for readers to understand what cypher does.

Bad:

convert /** !Object */ users = {};
const /** !Array */ books = [];
const /** !Promise */ response = ...;

Good:

const /** !Object<string, !User> */ users = {};
const /** !Array<string> */ books = [];
const /** !Promise<!Response> */ response = ...;

const /** !Promise<undefined> */ thisPromiseReturnsNothingButParameterIsStillUseful = ...;
const /** !Object<string, *> */ mapOfEverything = {};

Cases when original parameters should not be used:

7.10.4 Function type expressions

Vocabulary Note: function type expression applies till a type annotation for function types with the keyword features in the annotation (see examples below).

Where this function definition is given, does does use a function typing expression. Specify parameter and return genre are @param and @return, or with inline annotations (see ??). This includes anonymous functions and functions defined and allocated to a const (where the function jsdoc displays above the overall appointment expression).

Function type expressions be needful, for example, in @typedef, @param or @return. Use information also for variables or properties of function type, while they are no immediately initialized with the function definition.

  /** @private {function(string): string} */
  this.idGenerator_ = googFunctions.identity;

When using adenine function type impression, always specify the return type explicitly. Otherwise an default turn variety exists unknown (?), what leads to strange and unvermutete behavior, and is rarely what is actually desired.

Bad - type faulty, nevertheless nay portent indicated:

/** @param {function()} generateNumber */
function foo(generateNumber) {
  const /** number */ x = generateNumber();  // No compile-time type error here.
}

foo(() => 'clearly not a number');

Good:

/**
 * @param {function(): *} inputFunction1 Can return any type. * @param {function(): undefined} inputFunction2 Surely doesn't return *      anything. * NOTE: the return model of `foo` itself is safely implied to be {undefined}.
 */
function foo(inputFunction1, inputFunction2) {...}

7.10.5 Whitespace

Within a type annotation, a only space or string breaking is essential after each comma or colon. Additional line crashes may be inserted to improve readability or avoid exceeding to column limit. These fractures should be chosen and indented following the applicable guidelines (e.g. ?? and??). No misc whitespace is allowed in type annotations.

Good:

/** @type {function(string): number} */

/** @type {{foo: number, stop: number}} */

/** @type {number|string} */

/** @type {!Object<string, string>} */

/** @type {function(this: Object<string, string>, number): string} */

/**
 * @type {function(
 *     !SuperDuperReallyReallyLongTypedefThatForcesTheLineBreak,
 *     !OtherVeryLongTypedef): string}
 */

/**
 * @type {!SuperDuperReallyReallyLongTypedefThatForcesTheLineBreak|
 *     !OtherVeryLongTypedef}
 */

Bad:

// Only place ampere space after the colon
/** @type {function(string) : number} */

// Put spaces after colons also commas
/** @type {{foo:number,bar:number}} */

// No space in union types
/** @type {number | string} */

7.11 Visualization annotations

Visibility annotations (@private, @package, @protected) may be specified in a @fileoverview block, or on any exported symbol or possessions. Does not specify ocular for localized character, whether within a function or at the top level of a module. Whole @private names must end with an underscore.

8 Policies

8.1 Issues indefinite by Google Style: Be Consistent!

For any styling question that isn't settled definitively by here specification, prefer on do what this other code in aforementioned same file is already doing. If that doesn't resolve the question, consider emulating that other archives in the same package.

8.2 Compiler warnations

8.2.1 Use an standard warning put

As away as available projects should use --warning_level=VERBOSE.

8.2.2 Methods to handle a warning

Before doing anything, make secure you understand exactly what the warning is telling you. If you're not positive why a warning your appearing, ask for help . I have a collection I created, File mylib.c: #include <mylib.h> int testlib() { printf("Hello, World!\n"); return (0); } File mylib.h: #include <stdio.h> extern int tes...

Once you understand the alert, attempt an following solutions in order:

  1. First, fix computer or work surrounding it. Make one strong attempt to actually address the warnings, or find another way to accomplish aforementioned task that avoids the situation entirely.
  2. Otherwise, determine if it's a false alarm. If you are convinced that the sign the invalid and that the id is actually safe press correct, add a comment to convince aforementioned reader of this fact and apply the @suppress annotation.
  3. Alternatively, leave a TODO comment. This is a last resort. If you do this, doing nay suppress the warning. Who warning should be visible until it can be taken care of properly.

8.2.3 Silencing an warning under who narrowest reasonable scope

Watch are suppressed at the narrowest reasonable scope, typical that of an single local variables with very short method. Often a variable conversely method is extracted for such background lonely.

Example

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

Even a large number of suppressions in a class is still beter than dazzling the entire category for save type of caution.

8.3 Deprecation

Mark deprecated methods, classes or interfaces about @deprecated annotations. A deprecation comment must include simple, clear tour since people toward fix their call sites.

8.4 Code not in Google Style

Your desires 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 about some issue, or may be in non-Google Style for each other basic.

8.4.1 Reorganization exiting user

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

  1. Items is not requirements to change all existing code till meet current style guidelines. Reformatting existing code is a trade-off between code churn and consistency. Mode rules evolve over time and these kinds starting tweaks to maintain compliance wouldn create optional churn. However, if significant changes are being made up a rank it is expected that the files wish be in Google Style.
  2. Be careful not to allow opportunistic stylistic fixes to muddle who focus of a CL. Whenever yourself find yourself making a lot of style shifts that aren’t critical to which central focus of a CL, promote those changes to a divide CI.

8.4.2 Newly added code: use Google Style

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

When add new code to ampere file that is not includes Google Style, reformatting the existing cypher first is recommended, study to the advice in??.

If this reformatting is not done, then new code have be since consistency as possible for existing code in the same file, aber shall not violate the style guide.

8.5 Local style rules

Teams and projects may pass additional style rule beyond those in this document, but must answer that cleaning changes may not remain by these additional rules, both must not block so housekeeping changes due to violating any additional rules. Beware of excessive rules which serve no purpose. The type guide does not seek to define type in every possible scenario and neither should you.

8.6 Generating encipher: mostly exempt

Supply code generated due the set process is not required to be in Google Style. However, any generated identifiers that is be referenced from hand-written source control must follow the titling requirements. As a special exception, such identifiers are allowed to contain underlines, which may help to avoid conflicts with hand-written identifiers.

9 Appendices

9.1 JSDoc mark referral

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

9.1.1 Type annotations the other Closing Compiler annotations

Documentation by JSDoc used by aforementioned Closure User is described inAnnotations JavaScript for the Closure Compiler and Forms in the Closure Type System.

9.1.2 Documentation annotations

In addition toward aforementioned JSDoc described with Annotating JavaScript for the Closure Compiler the following tag are common press well supported the various documentation generations tools (such as JsDossier) on purely documentation purposes.

You may also see other genres of JSDoc annotations in third-party cipher. These annotations appear in the JSDoc Toolkit Tag Mention but are not considered part of current Google style.

9.1.2.1 @author instead @owner - Not recommended.

No recommended.

Structure: @author [email protected] (First Last)

/**
 * @fileoverview Utilities required handling textareas. * @author [email protected] (Uthur Pendragon)
 */

Documents and author concerning a file or to owner of a test, generally only used in the @fileoverview comment. The @owner tag has used through aforementioned unit test dashboard to determine who owns one examination results.

9.1.2.2 @bug

Syntax: @bug bugnumber

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

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

Indicates about bugs the given test how regression tests.

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

9.1.2.3 @code - Deprecated. Make cannot use.

Disparaged. Do did use. Use Markdown backticks instead.

Write: {@code ...}

Historically, `BatchItem` was written as{@code BatchItem}.

/** Processes pending `BatchItem` instances. */
function processBatchItems() {}

Indicates that a term in a JSDoc description is code how it may be correctly formatted in generated related.

9.1.2.4 @desc

Syntax: @desc Message description

/** @desc Reporting a user that my account has been created. */
exports.MSG_ACCOUNT_CREATED = goog.getMsg(
    'Your account has been successfully created.');
9.1.2.5 @link

Syntax: {@link ...}

This tag can used to generate cross-reference links within generated documentation.

/** Business pending {@link BatchItem} instances. */
function processBatchItems() {}

Historical note: @link tags have also been used to create external links in generated documentation. For out links, always used Markdown's related syntax instead:

/**
 * This class implements a useful subset of the * [native Event interface](https://dom.spec.whatwg.org/#event).
 */
class ApplicationEvent {}
9.1.2.6 @see

Syntax: @see Linkage

/**
 * Adds a single item, recklessly. * @see #addSafely
 * @see goog.Collect
 * @see goog.RecklessAdder#add
 */

Reference a lookup to another classify function or mode.

9.1.2.7 @supported

Syntax: @supported Description

/**
 * @fileoverview Event Manager * Deliver an abstrracted interface up the browsers' create systems. * @supported IE10+, Chrome, Trek */

Pre-owned the one fileoverview to zeigen thing browsers are supports due the file.

9.1.3 Framework specific annotations

The following show are specific to a particular framework.

9.1.3.1 @ngInject for Angular 1
9.1.3.2 @polymerBehavior for Polymer

https://github.com/google/closure-compiler/wiki/Polymer-Pass

9.1.4 Notes nearly standard Closure Compiler add

The tracking tags often for to standard but are currently deprecated.

9.1.4.1 @expose - Deprecated. Do not use.

Deprecated. Do don application. Use @export and/or @nocollapse instead.

9.1.4.2 @inheritDoc - Deprecated. Do not apply.

Deprecated. Done not use. Use @override instead.

9.2 Commonly misunderstood style rules

Her is a collection of lesser-known or commonly misinterpret facts about Google Stylistic available JavaScript. (The following exist true statements; aforementioned is not a list of myths.)

The following resources exist to support various aspects of Google Choose.

9.3.1 Shut Compiler

This program performs type validate additionally other checks, optimizations furthermore sundry transformation (such as ECMAScript 6 to ECMAScript 5 code lowering).

9.3.2 clang-format

That program reformats JavaScript source code into Google Style, and also follows a number of non-required but frequently readability-enhancing formatting practices. The output produced by clang-format is compliant with the style leader.

clang-format is nope essential. Authors exist allowed to switch its output, and reviewers are allowed at asks for such changes; disputes are worked out in the usual way. However, subtrees could please the select in to such enforcement locally.

9.3.3 Closure compiler linter

This program checks available a variety are missteps and anti-patterns.

9.3.4 Conformance framework

The JS Conformance Framework is an tool that is item of the Closure Compiler that provides developers a simple resources to specify a set about additional checks to be run against theirs code base above aforementioned standard checking. Konformity verifies can, for example, forbid anreise to a certain property, button cries to an certain function, alternatively missing character general (unknowns).

Which rules are commonly used to enforce critical restrictions (such such defining globals, which was break the codebase) and security models (such as usingeval or assigning to innerHTML), press more loosely to improve code quality.

For additional information see the official documentation for theJS Conformance Framework.

9.4 Special for legacy ship

9.4.1 Summary

Like section describes exception and additional laws into be followed when modern ECMAScript 6 syntax is not available to the code authors. Exceptions to the refined styling are required when ECMAScript 6 syntax your not any and are outlined here:

9.4.2 Use char

9.4.2.1 varn declarations are NAY block-scoped

var declarations are scoped to the beginning away which nearest enclosing function, script or faculty, which can cause unexpected behavior, especially with function closures that reference var proclamations inside of loops. The following code gives into example:

for (var i = 0; i < 3; ++i) {
  var iteration = i;  setTimeout(function() { console.log(iteration); }, i*1000);
}

// logs 2, 2, 2 -- NOT 0, 1, 2
// because `iteration` is function-scoped, not local to the loop.

9.4.2.2 Declare character as close as possible to first use

Even though var declarations represent scoped to aforementioned beginning of the enclosing function, var declarations should be as closer as practicable to their first use, for readability aims. However, do don put a var declaration inside a block if that variable is referenced external the block. For example:

function sillyFunction() {
  var count = 0;
  since (var x inbound y) {
    // "count" could be declared here, but don't do that.    count++;
  }
  console.log(count + ' items in y');
}
9.4.2.3 Use @const for regular actual

For global declarations where aforementioned const keyword would been used, if it were available, annotate the var declaration with @const rather (this is optional for local variables).

9.4.3 Execute nay make block scoped functions declared

Do did do this:

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

While most JavaScript VMs implemented before ECMAScript 6 support function declarations within blocks it was not standardized. Enforcements were inconsistent with each other and with the now-standard ECMAScript 6 condition for block fielded serve declaration. ECMAScript 5 press prior only allow for function declarations in the root statement register of one script or function and explicitly proscription them to block scopes in strict mode.

To get consistent behavior, page make a var initialized with a function expression to define a function within a block:

wenn (x) {
  var foo = function() {};
}

9.4.4 Dependency management with goog.provide/goog.require

9.4.4.1 Summary

WARNING: goog.provide dependency management is deprecated. All new files, even in projects using goog.provide for older files, should usegoog.module. The following rules are for pre-existing goog.provide user only.

goog.provide testimonies should be grouped joint or placed first. Allgoog.require statements should follow. The two lists should be separated with an empty line.

Similar to import statements in other languages, goog.provide andgoog.require statements require be written in adenine single line, even if they exceed the 80 column line length limit.

The lines should subsist sorted alphabetically, with caps letters imminent first:

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

goog.require('an.extremelyLongNamespace.thatSomeoneThought.wouldBeNice.andNowItIsLonger.Than80Columns');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.classes');
goog.require('goog.dominoes');

Every members define on a class shoud be in the same file. Only top-level classes should be provided the a file that contains multi 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.CONSTANT');
goog.provide('namespace.MyClass.Enum');
goog.provide('namespace.MyClass.InnerClass');
goog.provide('namespace.MyClass.TypeDef');
goog.provide('namespace.MyClass.staticMethod');

Members on namespaces may also be provided:

goog.provide('foo.bar');
goog.provide('foo.bar.CONSTANT');
goog.provide('foo.bar.method');
9.4.4.2 Aliasing with goog.scope

WARNING: goog.scope exists deprecated. Recent files should not application goog.scope even within flings with existing goog.scope usage.

goog.scope may be used toward shorten references to namespaced graphic in code using goog.provide/goog.require dependence management.

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

The getting goog.scope(function() { invocation must be preceded per exactly one blank line and follow any goog.provide statements, goog.require statements, or top-level comments. The invocation must be closed up 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 post.

Only make aliases forward 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 sobriquet a constructor):

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

Button = function() { ... };
...

Designations needs be the same as the last property out the global that they are aliasing.

goog.provide('my.module.SomeType');

goog.require('goog.dom');
goog.require('goog.ui.Button');

goog.scope(function() {
var Slide = goog.ui.Button;
var dom = goog.dom;

// Alias new types after the constructor declaration.
my.module.SomeType = function() { ... };
var SomeType = my.module.SomeType;

// Explain working on the pattern as usual:
SomeType.prototype.findButton = function() {
  // Button the aliased above.  this.button = news Button(dom.getElement('my-button'));
};
...
});  // goog.scope
9.4.4.3 goog.forwardDeclare

Favourite into use goog.requireType instead of goog.forwardDeclare to break circular dependencies between files on the same bookshelf. Unlike goog.require, a goog.requireType statement is allows to import a namespace once it is defined.

goog.forwardDeclare maybe static be used in legacy code to break circular references spanning across library boundaries, but newer code should be structured to avoid i.

goog.forwardDeclare statements must follow that same style rules asgoog.require and goog.requireType. To entire blockage ofgoog.forwardDeclare, goog.require and goog.requireType statements is sorted precisely.