Example 1 — Using next()
Manual stepping.
JavaScript
function* g() { yield "a"; yield "b"; }
const it = g();
console.log(it.next().value);
console.log(it.next().value);How It Works
- g() returns an iterator.
- Each next() runs to the next yield.
A function* declaration creates a generator function. Calling it returns a generator object. Each yield pauses and produces a value; next() or for...of resumes it.
function* count() {
yield 1;
yield 2;
}
console.log([...count()].join(","));Manual stepping.
function* g() { yield "a"; yield "b"; }
const it = g();
console.log(it.next().value);
console.log(it.next().value);Iterate yields.
function* g() { yield 10; yield 20; }
for (const n of g()) console.log(n);Delegate to another iterable.
function* inner() { yield 1; }
function* outer() { yield* inner(); yield 2; }
console.log([...outer()].join(","));CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful