What is Iterator in JavaScript: Simple Explanation and Example
iterator in JavaScript is an object that lets you access elements of a collection one at a time using a next() method. It returns each element in sequence until there are no more, making it easy to loop through data step-by-step.How It Works
Think of an iterator like a bookmark in a book. Instead of reading the whole book at once, you read one page at a time and keep your place with the bookmark. In JavaScript, an iterator keeps track of where you are in a list or collection and gives you the next item when you ask for it.
When you call the next() method on an iterator, it returns an object with two parts: the current value and a flag telling you if you have reached the end. This way, you can keep asking for the next item until there are no more left.
Many JavaScript objects like arrays, strings, and maps have built-in iterators, so you can use loops like for...of to go through their items easily.
Example
This example shows how to create a simple iterator for an array that returns each element one by one.
function createIterator(array) { let index = 0; return { next() { if (index < array.length) { return { value: array[index++], done: false }; } else { return { value: undefined, done: true }; } } }; } const colors = ['red', 'green', 'blue']; const iterator = createIterator(colors); console.log(iterator.next()); // { value: 'red', done: false } console.log(iterator.next()); // { value: 'green', done: false } console.log(iterator.next()); // { value: 'blue', done: false } console.log(iterator.next()); // { value: undefined, done: true }
When to Use
Use iterators when you want to process items one at a time without loading everything at once. This is helpful for large data sets or streams where you don’t want to use too much memory.
Iterators are also useful when you want to create custom ways to loop through your own data structures or when you want to control how and when items are accessed.
For example, reading lines from a file, generating infinite sequences, or handling user input step-by-step can all benefit from iterators.
Key Points
- An iterator provides a
next()method to get items one by one. - Each call to
next()returns an object withvalueanddoneproperties. - Built-in iterators exist for arrays, strings, maps, and more.
- Iterators help manage memory by processing data stepwise.
- You can create custom iterators for your own data structures.