[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/function* [Back]  [Original]

function* - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

function*

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2016 ..

function* ( function ) -.

In this article

function* name([param[, param[, ... param]]]) { statements }
name

.

param

(). - 255 .

statements

.

. ( ) .

-, ; -. next() - yield, yield* anotherGenerator(). next() value, , done, , . next() -, yield next().

js
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
// ...

yield*

js
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

js
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

return

js
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 }

(not constructable)

js
function* f() {}
var obj = new f(); // throws "TypeError: f is not a constructor"

Specification
ECMAScript 2027 LanguageSpecification
# sec-generator-function-definitions


Web Proxy Viewer  |  New URL  |  Original Page