Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

function* expression

BaselineWidely available

Thefunction* keyword can be used to define a generator function inside an expression.

You can also define generator functions using thefunction* declaration.

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

js
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

nameOptional

The function name. Can be omitted, in which case the function isanonymous. The name is only local to the function body.

paramNOptional

The name of a formal parameter for the function. For the parameters' syntax, see theFunctions reference.

statementsOptional

The 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:

js
const x = function* (y) {  yield y * y;};

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-generator-function-definitions

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp