ES6 Iteration Protocols
ES6 defines two protocols for iteration.
- Iterable Protocol
- Iterator Protocol
Iterable Protocol
Iteration can be done in an object if it is iterable by implementing @@iterator
using Symbol.iterator
. This implementation defines the iteration behavior of that object. That is the reason why iteration in an array is different from that in an object.
The expected behavior of an iterator function is called the iterator protocol.
Iterator Protocol
The iterator function is expected to return and object having a
next
function which can be called while iterating. The next
function when invoked, should return an object with properties done
, and value
.>
In that, done
is the status of the iterator and value
is the value returned in the current iteration.
See the example of an iterator function below,
Generators conform to iteration protocols and is useful in the implementation of these protocols.