5.5 Functions
5.5.1 Top-level functions
Top-level functions may be defined directly on the exports
object, or elsedeclared locally and optionally exported. 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 functions and closures
Functions may contain nested function definitions. If it is useful to give thefunction a name, it should be assigned to a local const
.
5.5.3 Arrow functions
Arrow functions provide a concise function syntax and simplify scoping this
for nested functions. Prefer arrow 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 const self = this
. Arrow functionsare particularly useful for calling into callbacks as they permit explicitlyspecifying which parameters to pass to the callback whereas binding will blindlypass along all parameters.
The left-hand side of the arrow contains zero or more parameters. Parenthesesaround the parameters are optional if there is only a single non-destructuredparameter. When parentheses are used, inline parameter types may be specified(see ??).
Tip: Always using parentheses even for single-parameter arrow functions canavoid situations where adding parameters, but forgetting to add parentheses, mayresult in parseable code which no longer works as intended.
The right-hand side of the arrow contains the body of the function. By defaultthe body is a block statement (zero or more statements surrounded by curlybraces). The body may also be an implicitly returned single expression ifeither: the program logic requires returning a value, or the void
operatorprecedes a single function or method call (using void
ensures undefined
isreturned, prevents leaking values, and communicates intent). The singleexpression form is preferred if it improves readability (e.g., for short orsimple expressions).
Examples:
/**
* Arrow functions can be documented just like normal functions.
* @param {number} numParam A number to add.
* @param {string} strParam Another number to add that happens to be a string.
* @return {number} The sum of the two parameters.
*/
const moduleLocalFunc = (numParam, strParam) => numParam + Number(strParam);
// Uses the single expression syntax with `void` because the program logic does
// not require returning a value.
getValue((result) => void alert(`Got ${result}`));
class CallbackExample {
constructor() {
/** @private {number} */
this.cachedValue_ = 0;
// For inline callbacks, you can use inline typing for parameters.
// Uses a block statement because the value of the single expression should
// not be returned and the expression is not a single function call.
getNullableValue((/** ?number */ result) => {
this.cachedValue_ = result == null ? 0 : result;
});
}
}
Disallowed:
/**
* A function with no params and no returned value.
* This single expression body usage is illegal because the program logic does
* not require returning a value and we're missing the `void` operator.
*/
const moduleLocalFunc = () => anotherFunction();
5.5.4 Generators
Generators enable a number of useful abstractions and may be used as needed.
When defining generator functions, attach the to the
function
keyword whenpresent, and separate it with a space from the name of the function. When usingdelegating yields, attach the to the
yield
keyword.
Example:
/** @return {!Iterator<number>} */
function* gen1() {
yield 42;
}
/** @return {!Iterator<number>} */
const gen2 = function*() {
yield* gen1();
}
class SomeClass {
/** @return {!Iterator<number>} */
* gen() {
yield 42;
}
}
5.5.5 Parameter and return types
Function parameters and return types should usually be documented with JSDocannotations. See ?? for more information.
5.5.5.1 Default parameters
Optional parameters are permitted using the equals operator in the parameterlist. Optional parameters must include spaces on both sides of the equalsoperator, be named exactly like required parameters (i.e., not prefixed withopt_
), use the =
suffix in their JSDoc type, come after required parameters,and not use initializers that produce observable side effects. All optionalparameters for concrete functions must have default values, even if that valueis undefined
. In contrast to concrete functions, abstract and interfacemethods must omit default parameter values.
Example:
/**
* @param {string} required This parameter is always needed.
* @param {string=} optional This parameter can be omitted.
* @param {!Node=} node Another optional parameter.
*/
function maybeDoSomething(required, optional = '', node = undefined) {}
/** @interface */
class MyInterface {
/**
* Interface and abstract methods must omit default parameter values.
* @param {string=} optional
*/
someMethod(optional) {}
}
Use default parameters sparingly. Prefer destructuring (as in??) to create readable APIs when thereare more than a small handful of optional parameters that do not have a naturalorder.
Note: Unlike Python's default parameters, it is okay to use initializers thatreturn new mutable objects (such as {}
or []
) because the initializer isevaluated each time the default value is used, so a single object won't beshared across invocations.
Tip: While arbitrary expressions including function calls may be used asinitializers, these should be kept as simple as possible. Avoid initializersthat expose shared mutable state, as that can easily introduce unintendedcoupling between function calls.
5.5.5.2 Rest parameters
Use a rest parameter instead of accessing arguments
. Rest parameters aretyped with a …
prefix in their JSDoc. The rest parameter must be the lastparameter in the list. There is no space between the …
and the parametername. Do not name the rest parameter var_args
. Never name a local variable orparameter arguments
, which confusingly shadows the built-in name.
Example:
/**
* @param {!Array<string>} array This is an ordinary parameter.
* @param {...number} numbers The remainder of arguments are all numbers.
*/
function variadic(array, ...numbers) {}
5.5.6 Generics
Declare generic functions and methods when necessary with @template TYPE
inthe JSDoc above the function or method definition.
5.5.7 Spread operator
Function calls may use the spread operator (…
). Prefer the spread operatorto Function.prototype.apply
when an array or iterable is unpacked intomultiple parameters of a variadic function. There is no space after the …
.
Example:
function myFunction(...elements) {}
myFunction(...array, ...iterable, ...generator());