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 codebyte example below to see how an iterator works with a string:
All contributors
- LunaLlenaDeAmor
- Anonymous contributor
- BrandonDusch
- christian.dinh
- Anonymous contributor
- Christine_Yang
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.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours