Iterators in JavaScript provide a standard way to access elements of a collection one by one.
They are used internally by loops like for...of and help you build custom iteration logic for your own data structures.
What Are Iterators in JavaScript?
An iterator is an object that follows a specific structure:
-
It has a
next()method -
next()returns an object with:-
value→ current item -
done→truewhen iteration is finished
-
Iterators allow controlled traversal of data.
Built-in Iterators with for...of
Many JavaScript structures are iterable:
-
Arrays
-
Strings
-
Sets
-
Maps
Explanation:
-
for...ofuses the iterator behind the scenes -
It reads values one by one
-
Stops automatically when iteration is complete
Using an Iterator Manually
Output:
Explanation:
-
Symbol.iterator()returns an iterator object -
Each
next()call moves to the next value -
When items end,
donebecomestrue
Creating a Custom Iterator
Explanation:
-
Symbol.iterator()defines how iteration works -
next()controls the sequence -
for...ofreads values from the iterator
Why Iterators Are Important
Understanding JavaScript iterators helps you:
-
Work with modern loops
-
Build custom iterable objects
-
Control data traversal
-
Write cleaner iteration logic
-
Understand generators and async iteration
Quick Summary
-
Iterators return
{ value, done } -
for...ofuses iterators internally -
Symbol.iterator()creates iterators -
You can build custom iteration logic
-
Used in arrays, strings, sets, and maps
Conclusion
Iterators in JavaScript provide a powerful and flexible way to traverse data.
They form the foundation of modern iteration patterns and help you build clean, reusable iteration logic in real-world applications.