JavaScript Iterators and Generators
Learn JavaScript through interactive, bite-sized lessons. Practice with real code challenges and build projects step-by-step.
Start JavaScript Journey →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.
Iterators
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.
Creating an Iterator
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
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.
Creating a Generator
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.
Use Cases
- Lazy evaluation of sequences
- Processing large datasets efficiently
- Implementing custom iteration behavior for objects
- Managing asynchronous operations
Iterables
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
Best Practices
- Use generators for creating complex iterators
- Implement the iterable protocol for custom objects that should be iterable
- Leverage iterators and generators for efficient data processing
- Consider using generators for asynchronous programming with async/await
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.