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

  1. value: the return value.
  2. done: boolean value. If it is false then iterator can return next values and if it is true 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]

References

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol