Iterators
Iterators are used to loop over a group of data members, or a collection.
An iterator is an object that implements the iteration protocols. Many built-in data types (strings, arrays, maps, sets, etc.) have an iterator property that make them iterable.
Iterable and Iterator Protocols
The iterable protocol stipulates that all iterable objects implement the @@iterator
method. In other words, an object must have or inherit, via its prototype chain, the @@iterator
property key. When an object is to be iterated, the @@iterator
method is called without any arguments, and the returned iterator obtains the values or elements to be looped over.
The iterator protocol, by definition, implements the next()
method and returns an object with at least two properties:
done
is a boolean that determines whether the sequence has been completed or consumed. If incomplete, its value isfalse
. Otherwise, it istrue
.value
is any type of value the iterator returns.
Example
This range-based iterator, loops through a collection of integers and satisfies the iteration protocols.
function createRangeIterator(min = 0, max = Infinity, step = 1) {let nextNum = min;let numCount = 0;const rangeIterator = {next: function () {let result;if (nextNum < max) {result = { value: nextNum, done: false };nextNum += step;numCount++;return result;}return { value: numCount, done: true };},};return rangeIterator;}
- The
rangeIterator
object is an iterator object that satisfies the iterator protocol. - When all elements in the range collection are iterated over,
done
becomestrue
and is returned.
To use the createRangeIterator()
:
const useCase = createRangeIterator(2, 8, 2);let result = useCase.next();while (!result.done) {console.log(result.value);result = useCase.next();}
This will output:
246
Codebyte Example
Run the below codebyte example to see how an iterator works with a string:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.