How do generators work in JavaScript?
Asked on Jul 27, 2024
Answer
Generators in JavaScript are special functions that can be paused and resumed, allowing you to iterate over a sequence of values. They are defined using the "function*" syntax and use the "yield" keyword to produce values.
// Define a generator function
function* simpleGenerator() {
yield 1;
yield 2;
yield 3;
}
// Create an iterator from the generator
const iterator = simpleGenerator();
console.log(iterator.next().value); // Output: 1
console.log(iterator.next().value); // Output: 2
console.log(iterator.next().value); // Output: 3
console.log(iterator.next().done); // Output: true
Additional Comment:
✅ Answered with JavaScript best practices.- Generators are defined with the "function*" syntax.
- Use "yield" to pause the function and return a value.
- The "next()" method resumes the generator and returns an object with "value" and "done" properties.
- Generators are useful for creating iterators and handling asynchronous operations.
Recommended Links:
← Back to All Questions