Master ES6 Iterators for Clean JavaScript Code
ES6 introduced the Iterator interface, enabling sequential access to iterable objects like Arrays, Sets, Maps, Strings, arguments, and custom objects. Iterators provide a standardized way to traverse data structures and are essential for for...of
loops. In this guide, you'll learn how to use ES6 iterators to write clean, efficient JavaScript code. We'll cover the basics of iterators, how to create custom iterators, and how to use generator functions to simplify iteration patterns. Let's get started!
1. What is an Iterator?
An iterator is an object with a next()
method that returns:
done: false
→ More values remain.done: true
→ Iteration is complete.
Iteration Process:
- Create an iterator pointing to the start of the data structure.
- Call
next()
to move to the first element. - Keep calling
next()
to traverse through elements. - Stops when
done: true
is returned.
2. How to Create an Iterator
(1) Manually Implement an Iterator
📌 Each call to next()
returns a value and moves forward.
(2) Use Symbol.iterator
for Built-in Iterables
All iterable objects (Array
, Set
, Map
, String
) have a default iterator accessible via Symbol.iterator
.
📌 Arrays, Strings, Sets, and Maps can be iterated directly.
(3) Create an Iterator for a Custom Object
Ordinary objects are not iterable by default but can be made iterable using Symbol.iterator
.
📌 Objects require Symbol.iterator
to be iterable with for...of
.
3. How to Use for...of
for Iteration
All objects implementing Symbol.iterator
can be traversed using for...of
.
📌 Unlike forEach()
, for...of
allows break
and continue
.
4. What Are Iterable Objects?
✅ Objects supporting for...of
via Symbol.iterator
:
Array
String
Set
Map
arguments
NodeList
- Custom objects (with
Symbol.iterator
implemented)
5. How to Iterate Over Set
and Map
(1) Iterate Over a Set
📌 Set maintains insertion order and ensures unique values.
(2) Iterate Over a Map
📌 Map
iteration returns [key, value]
pairs.
6. How Iterators Compare to Generators
The key differences between Iterators and Generators lie in their creation and execution patterns. For creation, Iterators require manual implementation of the next()
function and Symbol.iterator
, making them more verbose to write. Generators, on the other hand, use the function* syntax which automatically generates these implementations, significantly reducing boilerplate code.
When it comes to execution, Iterators run without pausing – they process their elements continuously until completion. In contrast, Generators support the yield keyword, allowing them to pause execution and resume later. This makes Generators particularly useful for controlling flow and managing memory in large datasets or infinite sequences.
Example: Using a Generator
📌 Generators simplify iteration with yield
and can pause execution.
7. Best Practices for Using Iterators
(1) Implement Iterators in a Class
(2) Use Asynchronous Iterators (ES2018)
8. When to Use Iterators
✅ Iterators are useful for:
- Traversing arrays, strings, sets, and maps
- Creating custom iterable objects
- Handling streaming data (e.g., paginated API responses)
- Avoiding memory-heavy operations by using generators
9. Conclusion
- Iterators
(Symbol.iterator
) provide a structured way to access collections. for...of
simplifies iteration over iterable objects.- Generators (
function*
) create iterators effortlessly with yield. - Asynchronous Iterators (
Symbol.asyncIterator
) handle streaming data efficiently.
Mastering iterators will make your JavaScript code more efficient and readable! 🚀