Generator return value
Short answer:
Calling a generator function (
function*) does not run its code immediately.It returns a generator object, which is an iterator and controls the execution of that function.
Example
javascript
function* gen() {
yield 1;
yield 2;
yield 3;
}
const iterator = gen(); // a generator object is returned
console.log(iterator); // Object [Generator] {}The iterator object is not the function's result,
but a controller that lets you run the generator "step by step" via .next(), .throw(), .return().
What the generator object can do
A generator implements two protocols:
- The iterator protocol (
next(),done,value); - The iterable protocol (
[Symbol.iterator]()).
Example of working with .next()
javascript
function* gen() {
yield 'A';
yield 'B';
}
const it = gen();
console.log(it.next()); // { value: 'A', done: false }
console.log(it.next()); // { value: 'B', done: false }
console.log(it.next()); // { value: undefined, done: true }Each call to .next():
- starts the generator (if it is "frozen");
- runs it until the next
yieldorreturn; - returns the object
{ value, done }.
A generator is an iterator
A generator can be used in for...of, spread, Array.from and other iterations:
javascript
function* gen() {
yield 1;
yield 2;
yield 3;
}
const iterator = gen();
for (const n of iterator) {
console.log(n);
}Output:
javascript
1
2
3The generator object has 3 methods
| Method | What it does |
|---|---|
.next(value) | Resumes execution until the next yield; returns { value, done } |
.throw(error) | Throws an exception inside the generator (caught via try/catch) |
.return(value) | Ends the generator and returns { value, done: true } |
A generator is not the same as the function's result
It's important to understand:
javascript
function* numbers() {
yield 1;
yield 2;
}
const result = numbers(); // returns not [1,2], but a generator objectTo get the actual values, you need to "walk" the generator:
javascript
console.log([...numbers()]); // [1, 2]or manually call .next() several times.
Visually:
javascript
┌────────────────────┐
│ function* numbers()│
│ { yield 1; yield 2;}│
└────────┬───────────┘
│ call
▼
┌───────────────────────────────┐
│ Object [Generator] │
│ ├── next() │
│ ├── throw() │
│ ├── return() │
│ └── [Symbol.iterator]() │
└───────────────────────────────┘Summary
| What a generator returns | Generator object |
|---|---|
| Runs immediately? | No |
| Can execution be controlled? | Yes, via .next() |
| Implements the iterator protocol? | Yes |
| Returns values? | Via yield |
Can be used in for...of | Yes |
| Returns a final value | Via return or done: true |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.