JavaScript 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:
doneis a boolean that determines whether the sequence has been completed or consumed. If incomplete, its value isfalse. Otherwise, it istrue.valueis 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
rangeIteratorobject is an iterator object that satisfies the iterator protocol. - When all elements in the range collection are iterated over,
donebecomestrueand 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
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours