function* expression
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.
Thefunction* keyword can be used to define a generator function inside an expression.
You can also define generator functions using thefunction* declaration.
In this article
Try it
const foo = function* () { yield "a"; yield "b"; yield "c";};let str = "";for (const val of foo()) { str += val;}console.log(str);// Expected output: "abc"Syntax
function* (param0) { statements}function* (param0, param1) { statements}function* (param0, param1, /* …, */ paramN) { statements}function* name(param0) { statements}function* name(param0, param1) { statements}function* name(param0, param1, /* …, */ paramN) { statements}Note:Anexpression statement cannot begin with the keywordfunction to avoid ambiguity with afunction* declaration. Thefunction keyword only begins an expression when it appears in a context that cannot accept statements.
Parameters
nameOptionalThe function name. Can be omitted, in which case the function isanonymous. The name is only local to the function body.
paramNOptionalThe name of a formal parameter for the function. For the parameters' syntax, see theFunctions reference.
statementsOptionalThe statements which comprise the body of the function.
Description
Afunction* expression is very similar to, and has almost the same syntax as, afunction* declaration. The main difference between afunction* expression and afunction* declaration is thefunction name, which can be omitted infunction* expressions to createanonymous functions. Afunction* expression can be used as anIIFE (Immediately Invoked Function Expression) which runs as soon as it is defined, allowing you to create an ad-hociterable iterator object. See also the chapter aboutfunctions for more information.
Examples
>Using function* expression
The following example defines an unnamed generator function and assigns it tox. The function yields the square of its argument:
const x = function* (y) { yield y * y;};Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-generator-function-definitions> |