Generator functions
Learn to define a generator with function* and the generator object.
Generator functions
A generator is a special function that, instead of producing all values at once, yields them one by one as the caller requests. You define it with the function* syntax; the asterisk marks it as a generator rather than a regular function.
function* counter() {
yield 1;
}
const gen = counter();Calling a generator does not run its code right away. Instead, it returns a generator object that holds the execution state. You use this object to pull values one at a time.
function* versus a regular function
A regular function runs its body immediately and returns a value. A generator, when called, does not run its body; it returns a generator object instead. The code runs step by step only when .next() is called.
function* greeter() {
yield 'hello';
}
const g = greeter();
g.next(); // { value: 'hello', done: false }This lazy behavior saves memory with large or infinite sequences.
Exercise Write your first generator
Write a generator function named counter with a yield 1 expression inside. Create a generator object called gen. Call console.log(gen.next()) to log the result.
Show example solution
function* counter() {
yield 1;
}
const gen = counter();
console.log(gen.next());
Test yourself
-
Which is a valid generator function definition?
- function counter*() {}
- function generator counter() {}
- function* counter() {}
- generator function counter() {}
Show answer
function* counter() {} — Correct! The function* syntax is the standard way to define a generator.
-
Create the generator object
function* counter() { yield 1; } const gen = ____;Show answer
function* counter() { yield 1; } const gen = counter(); -
Match the generator concepts
- function*
- defines a generator
- generator object
- returns next()
- lazy
- runs when called