javascript

Working with Iterators


Iterators is used to iterate over collections of data, such as arrays or strings, in a flexible and controlled manner. Iterator is an in-built iterator protocols that enable us to create and work with iterators.

 

Creating Iterators:

You can create custom iterators for objects by defining an iterator function that returns an object conforming to the iterator protocol. This object must have a next() method that returns an object with value and done properties.

 

Example:

function customIterator(arr) {
    let index = 0;

    return {
        next: function() {
            return index < arr.length ? { 
                value: arr[index++], done: false 
            } : { done: true };
        }
    };
}

const iterator = customIterator([1, 2, 3]);

console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { done: true }

 

Explanation:

  1. We define an iterable object with an array of data and a custom iterator function that returns an iterator object.
  2. The iterator object has a next() method that returns the next value in the sequence.
  3. We use a for...of loop to iterate over the iterable object, which internally calls the next() method of the iterator until it reaches the end of the sequence.

 

Iterators are iterable over data structures like arrays, strings, maps, sets, etc., which can be iterated over using the for...of loop or by explicitly calling their iterator methods (values(), keys(), entries()).