W3cubDocs

/JavaScript

Generator

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

Constructor

This object cannot be instantiated directly. Instead, a Generator instance can be returned from a generator function:

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

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

Instance methods

Generator.prototype.next()
Returns a value yielded by the yield expression.
Generator.prototype.return()
Returns the given value and finishes the generator.
Generator.prototype.throw()
Throws an error to a generator (also finishes the generator, unless caught from within that generator).

Examples

An infinite iterator

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 compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
Generator 39 13 26 No 26 10
next 39 13 26 No 26 10
return 50 13 38 No 37 10
throw 39 13 26 No 26 10
Mobile
Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Generator 39 39 26 26 10 4.0
next 39 39 26 26 10 4.0
return 50 50 38 37 10 5.0
throw 39 39 26 26 10 4.0
Server
Node.js
Generator 4.0.0
4.0.0
0.12
Disabled
Disabled From version 0.12: this feature is behind the --harmony runtime flag.
next Yes
return 6.0.0
throw 4.0.0
4.0.0
0.12
Disabled
Disabled From version 0.12: this feature is behind the --harmony runtime flag.

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator