| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/function* | [Back] [Original] |
Get to know MDN better
This page was translated from English by the community. Learn more and join the MDN Web Docs community.
This feature is well established and works across many devices and browser versions. Its been available across browsers since 2016 ..
function* ( function ) -.
function* name([param[, param[, ... param]]]) { statements }
name.
param(). - 255 .
statements.
. ( ) .
-, ; -. next() - yield, yield* anotherGenerator(). next() value, , done, , . next() -, yield next().
function* idMaker() {
var index = 0;
while (index < 3) yield index++;
}
var gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // undefined
// ...
function* anotherGenerator(i) {
yield i + 1;
yield i + 2;
yield i + 3;
}
function* generator(i) {
yield i;
yield* anotherGenerator(i);
yield i + 10;
}
var gen = generator(10);
console.log(gen.next().value); // 10
console.log(gen.next().value); // 11
console.log(gen.next().value); // 12
console.log(gen.next().value); // 13
console.log(gen.next().value); // 20
function* logGenerator() {
console.log(yield);
console.log(yield);
console.log(yield);
}
var gen = logGenerator();
// next
// yield
gen.next();
gen.next("pretzel"); // pretzel
gen.next("california"); // california
gen.next("mayonnaise"); // mayonnaise
function* yieldAndReturn() {
yield "Y";
return "R";
yield "unreachable";
}
var gen = yieldAndReturn();
console.log(gen.next()); // { value: "Y", done: false }
console.log(gen.next()); // { value: "R", done: true }
console.log(gen.next()); // { value: undefined, done: true }
function* f() {}
var obj = new f(); // throws "TypeError: f is not a constructor"
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-generator-function-definitions |
This page was last modified on 24 . 2025 . by MDN contributors.
Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |