JavaScript Generator Object
A Generator is the object returned by a generator function (function*). It produces a sequence of values on demand with yield, pausing between each one.
Description
A Generator object is returned when you call a generator function, declared with function*. The function's body doesn't run straight away; each call to the generator's next() method runs it until the next yield expression, which hands back a value and pauses the function until next() is called again.
Generators are iterators, so they work with for...of, spread syntax and iterator helpers. They are a simple way to create custom sequences, including infinite ones, and to write lazy pipelines. return() ends a generator early and throw() injects an error at the paused yield. Async generators (async function*) produce values over time and are consumed with for await...of.
Generator objects are both iterators and iterables, so they can be passed anywhere an iterable is expected, but like other iterators they can only be consumed once. Each call to the generator function creates a new, independent generator. Because their bodies only run on demand, generators are memory-efficient for large or computed sequences, such as reading records one at a time.
Creating
function* name() { yield value; }Example
Browser Support
The following information will show you the current browser support for the Generator object. Hover over a browser icon to see the version that first introduced support for this object.
Desktop





Tablets & Mobile





