JavaScript Reference ยท Iterators, Generators and Symbols
The iterator protocol
Reference for the JavaScript iterator protocol: the next() method, result objects with value and done, optional return() cleanup, and hand-written iterators.
The iterator protocol is a convention for producing a sequence of values one at a time. An object is an iterator if it has a next() method that returns an object with two properties: value (the next item) and done (a boolean saying whether the sequence has ended).
That is all there is to it. Nothing needs to inherit from a special class. Arrays, strings, maps, sets and generators produce iterators, and language features such as for...of and spread consume them by calling next() repeatedly. To make an object usable in those features, you also need the iterable protocol.
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
The result object
| Property | Meaning |
|---|---|
done |
false while more values may follow; true when the iterator has finished. If omitted, it counts as false. |
value |
The current item. When done is true, it is the iterator's return value, usually undefined. |
Consumers stop at the first result with done: true and ignore its value. That is why [...countdown(2)] is [2, 1] and not [2, 1, undefined].
Once an iterator has reported done: true, it should keep doing so on later calls to next().
Optional methods
An iterator may also implement:
return(value), called when a consumer stops early:break,returnorthrowinsidefor...of, or destructuring that takes fewer items than exist. Use it to release resources such as file handles. It must return an object; a normal finish does not call it.throw(error), used mainly by generators to inject an error at the paused point.
See generator objects for both in action.
Usage notes
- Iterators are usually single-use. After
done: true, you need a new iterator to start over; that is what the iterable protocol provides. - Iterators are lazy. Values can be computed on demand, so a sequence can even be infinite.
- Built-in iterators (from
array.values(),map.entries(), generators) also inherit helper methods; see iterator helpers. - Return a fresh result object each time or reuse one on purpose; consumers read it immediately, but sharing mutable results between calls can confuse callers who keep them.
next()may take an argument, which generators use to receive values (it.next(x)); most simple iterators ignore it.- Do not confuse the iterator with the thing it iterates: an array is iterable,
array[Symbol.iterator]()is the iterator. - Errors thrown by
next()propagate to the consumer, which stops iterating without callingreturn().
Browser support
The iterator protocol is part of ES2015 and works in every current browser and in Node.js.