Iterators and generators are powerful features in JavaScript that enhance how we work with collections and create custom iteration behavior. They provide elegant solutions for handling complex data structures and asynchronous operations.
An iterator is an object that defines a next()
method, which returns an object with value
and done
properties. Iterators allow you to traverse a collection one item at a time.
const myIterator = {
data: [1, 2, 3],
index: 0,
next() {
if (this.index < this.data.length) {
return { value: this.data[this.index++], done: false };
}
return { done: true };
}
};
console.log(myIterator.next()); // { value: 1, done: false }
console.log(myIterator.next()); // { value: 2, done: false }
console.log(myIterator.next()); // { value: 3, done: false }
console.log(myIterator.next()); // { done: true }
Iterators are the foundation for many built-in JavaScript features, including for...of loops and the spread operator.
Generators are special functions that can be paused and resumed, making them perfect for creating iterators. They use the function*
syntax and the yield
keyword to define iteration behavior.
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}
const gen = numberGenerator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
Generators simplify the creation of iterators and are particularly useful for working with large or infinite sequences.
An iterable is an object that implements the Symbol.iterator
method, which returns an iterator. Many built-in JavaScript objects, like arrays and strings, are iterable.
const myIterable = {
*[Symbol.iterator]() {
yield 'Hello';
yield 'World';
}
};
for (const value of myIterable) {
console.log(value);
}
// Output:
// Hello
// World
Iterators and generators are powerful tools in JavaScript that can significantly improve code readability and performance when working with collections or custom iteration scenarios. By mastering these concepts, you'll be able to write more efficient and elegant code.