Iterators and iterables
ES6 introduces a new mechanism of iterating over data. Traversing a list of data and doing something with it is a very common operation. ES6 enhances the iteration constructs. There are two primary concepts involved with this change-iterators and iterables.
Iterators
A JavaScript iterator is an object that exposes the next()
method. This method returns the next item from the collection in the form of an object that has two properties-done
and value
. In the following example, we will return an iterator from an array by exposing the next()
method:
//Take an array and return an iterator function iter(array){ var nextId= 0; return { next: function() { if(nextId < array.length) { return {value: array[nextId++], done: false}; } else { return {done: true}; } } } } var it = iter(['Hello', 'Iterators...