5.1 Local variable declarations

5.1.1 Use const and let

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

5.1.2 One variable per declaration

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

5.1.3 Declared when needed, initialized as soon as possible

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

5.1.4 Declare types as needed

JSDoc type annotations may be added either on the line above the declaration, orelse inline before the variable name if no other JSDoc is present.

Example:

  1. const /** !Array<number> */ data = [];
  2. /**
  3. * Some description.
  4. * @type {!Array<number>}
  5. */
  6. const data = [];

Mixing inline and JSDoc styles is not allowed: the compiler will only processthe first JsDoc and the inline annotations will be lost.

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

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