Intermediate LevelJavaScript & TypeScript
How do JavaScript Generators (function*) and Iterators work (Symbol.iterator)?
❓ Interview Prompt: Explain generator functions, yield keyword, Iterator protocol ({value, done}), and custom iterable objects.
Generators are special functions declared with function* that can pause execution (yield) and resume later, maintaining state between invocations.
Iterator Protocol:
An object is an iterator if it implements a .next() method returning { value: any, done: boolean }.
Iterable Protocol:
An object is iterable if it implements [Symbol.iterator]() returning an iterator. Enables for...of loops and spread operator.
Code Implementation Example
javascript
// Generator function generating infinite IDs
function* idGenerator() {
let id = 1;
while (true) {
yield id++;
}
}
const gen = idGenerator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
// Custom Iterable Object
const customCollection = {
items: ['a', 'b', 'c'],
*[Symbol.iterator]() {
for (const item of this.items) yield item.toUpperCase();
}
};
for (const val of customCollection) {
console.log(val); // "A", "B", "C"
}💡Infinite ID generator function and custom iterable object via Symbol.iterator.
🎯 Interview Key Takeaway
Generators pause with yield and resume with next(). Implementing Symbol.iterator makes objects compatible with for...of loops.
#Generators#Iterators#ES6#Intermediate
Back to all JavaScript & TypeScript Questions→