JavaScript Interview Question #126
What is a generator function in JavaScript?
Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced
Quick Interview Answer
A generator function is declared with function* and can pause and resume its execution using the yield keyword. Calling a generator function does not immediately execute its body; it returns a generator object that implements the iterator protocol.
Detailed Explanation
A generator function is declared with function* and can pause and resume its execution using the yield keyword. Calling a generator function does not immediately execute its body; it returns a generator object that implements the iterator protocol.
Each call to next() resumes execution until the next yield or until the function finishes. Generators are useful for custom iteration, lazy sequences, state machines, and processing sequences without creating all values in memory at once.
Code Example
function* numbers() {
yield 1;
yield 2;
yield 3;
}
const iterator = numbers();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }