CKTIS / JavaScript
Generator function declaration and generator method
Both forms define synchronous generator functions. A declaration introduces a name in scope, while a method belongs to an object or class.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
function* sequence(start) { yield start; }
const object = { *values() { yield this.start; } };
class Series { *values() { yield this.start; } }A declaration such as function* sequence(start) { ... } binds the name sequence in its scope. The form *values() { ... } defines a method in an object or class: the asterisk goes before the method name, and there is no function keyword. In the call counter.values(), this inside the method is counter.
Calling either form returns a fresh synchronous generator, which is both an iterator and an iterable. Statements in the body do not run until the first next(). A yield value pauses execution, preserves local state, and produces a result of the form { value, done: false }. The next next() call resumes execution. Using new with either function throws a TypeError.
If next() reaches return value, its result is { value, done: true }. A for...of loop or spread syntax ... consumes the yielded values but omits that final return value. Once the generator is finished, further calls to next() return { value: undefined, done: true }. To start over, call the function or method again.
Examples
{
function* sequence(start) {
yield start;
return start + 1;
}
const counter = {
start: 7,
*values() {
yield this.start;
},
};
const steps = sequence(3);
for (let i = 0; i < 3; i++) {
const { value, done } = steps.next();
console.log(`${value} ${done}`);
}
console.log(JSON.stringify([...counter.values()]));
}Result
3 false 4 true undefined true [7]
The `next()` calls show the yielded `3`, the returned `4`, and then the exhausted state. Spreading the generator from `counter.values()` gives `[7]` because the method reads `counter.start` through `this`.
Related lessons
- JavaScript · Lesson 8 · Advanced · Version: 4