W3cubDocs

/JavaScript

Generator

The Generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.

Try it

Constructor

The Generator constructor is not available globally. Instances of Generator must be returned from generator functions:

function* generator() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = generator(); // "Generator { }"

console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

Instance methods

Generator.prototype.next()

Returns a value yielded by the yield expression.

Generator.prototype.return()

Acts as if a return statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a try...finally block.

Generator.prototype.throw()

Acts as if a throw statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.

Examples

An infinite iterator

With a generator function, values are not evaluated until they are needed. Therefore a generator allows us to define a potentially infinite data structure.

function* infinite() {
  let index = 0;

  while (true) {
    yield index++;
  }
}

const generator = infinite(); // "Generator { }"

console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
// …

Specifications

Browser compatibility

Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet Deno Node.js
Generator
39
13
26
No
26
10
39
39
26
26
10
4.0
1.0
4.0.0
0.12.0
next
39
13
26
No
26
10
39
39
26
26
10
4.0
1.0
4.0.0
0.12.0
return
50
13
38
No
37
10
50
50
38
37
10
5.0
1.0
6.0.0
throw
39
13
26
No
26
10
39
39
26
26
10
4.0
1.0
4.0.0
0.12.0

See also

© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator