Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
A generator is a special function that can pause execution and resume later. Use function* syntax and yield to return multiple values over time!
// Returns all at once
function getNumbers() {
return [1, 2, 3, 4, 5];
}
const nums = getNumbers();
console.log(nums); // [1, 2, 3, 4, 5]
// Must create iterator manually
function createIterator() {
let index = 0;
const arr = [1, 2, 3, 4, 5];
return {
next() {
if (index < arr.length) {
return { value: arr[index++], done: false };
}
return { done: true };
}
};
}// function* creates generator
function* getNumbers() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
}
const nums = getNumbers();
console.log(nums.next()); // { value: 1, done: false }
console.log(nums.next()); // { value: 2, done: false }
console.log(nums.next()); // { value: 3, done: false }
// Works with for...of!
for (const num of getNumbers()) {
console.log(num); // 1 2 3 4 5
}function* and yield in action
function* gen1() {
yield 1;
yield 2;
}
function* gen2() {
yield 3;
yield 4;
}
// Manually combining
function* combined1() {
for (const value of gen1()) {
yield value;
}
for (const value of gen2()) {
yield value;
}
}
// Using yield* (cleaner!)
function* combined2() {
yield* gen1();
yield* gen2();
}
console.log([...combined2()]); // [1, 2, 3, 4]
// Works with any iterable
function* letters() {
yield* 'ABC'; // String is iterable
yield* [1, 2, 3]; // Array is iterable
}
console.log([...letters()]); // ['A', 'B', 'C', 1, 2, 3]Delegating to other generators
function* conversation() {
const name = yield 'What is your name?';
const age = yield `Hello ${name}! How old are you?`;
return `${name} is ${age} years old`;
}
const chat = conversation();
console.log(chat.next().value);
// 'What is your name?'
console.log(chat.next('Alice').value);
// 'Hello Alice! How old are you?'
console.log(chat.next(25).value);
// 'Alice is 25 years old'
// Practical example: alternating values
function* alternator() {
let toggle = true;
while (true) {
toggle = yield toggle;
}
}
const alt = alternator();
console.log(alt.next().value); // true
console.log(alt.next(false).value); // false
console.log(alt.next(true).value); // truethrow() and return() methods
Lazy loading pages of data
Use function* and yield
Execution pauses at each yield
Generators return iterators
Works with for...of, spread, destructuring
next(value) sends values inthrow() and return() control flow
Delegate to other generators/iterables
Perfect for composition