Iterable and Iterator
An iterable is an object which can be used in for..of
and spread
functions. Iterable objects can be looped over their values. To make objects iterable, they have implement [Symbol.Iterator]
method which returns an iterator.
An iterator is an object which can produce a sequence of values either definitely or indefinitely. An iterator object implements iterator protocol where it has to have next
method. Semantic of this method is as follows,
next()
can accept zero or one argument and it returns IteratorResult
.
IteratorResult
is an object with two information
value
: the return value.done
: boolean value. If it isfalse
then iterator can return next values and if it istrue
then iterator is exhausted.
Both values are optional. If not provide value
becomes undefined
and done
becomes true
.
Example
> iterable = {
[Symbol.iterator]: () => {
iterator = {
current: 0,
values: [1, 2, 3],
next() {
if (this.current >= this.values.length) {
return {done: true};
}
return {value: this.values[this.current++], done: false};
}
}
return iterator;
}
}
>[...iterable]
[1, 2, 3]