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.
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.
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 }
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()).