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

    • donetrue when iteration is finished

Iterators allow controlled traversal of data.


Built-in Iterators with for...of

Many JavaScript structures are iterable:

  • Arrays

  • Strings

  • Sets

  • Maps

JavaScript
1let numbers = [10, 20, 30];
2
3for (let num of numbers) {
4 console.log(num);
5}
6

Explanation:

  • for...of uses the iterator behind the scenes

  • It reads values one by one

  • Stops automatically when iteration is complete


Using an Iterator Manually

JavaScript
1let list = ["a", "b", "c"];
2let iterator = list[Symbol.iterator]();
3
4console.log(iterator.next());
5console.log(iterator.next());
6console.log(iterator.next());
7console.log(iterator.next());
8

Output:

JavaScript
1{ value: "a", done: false }
2{ value: "b", done: false }
3{ value: "c", done: false }
4{ value: undefined, done: true }

Explanation:

  • Symbol.iterator() returns an iterator object

  • Each next() call moves to the next value

  • When items end, done becomes true


Creating a Custom Iterator

JavaScript
1let counter = {
2 start: 1,
3 end: 3,
4 [Symbol.iterator]() {
5 let current = this.start;
6 let last = this.end;
7
8 return {
9 next() {
10 if (current <= last) {
11 return { value: current++, done: false };
12 }
13 return { value: undefined, done: true };
14 }
15 };
16 }
17};
18
19for (let num of counter) {
20 console.log(num);
21}
22

Explanation:

  • Symbol.iterator() defines how iteration works

  • next() controls the sequence

  • for...of reads 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...of uses 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.