Iterators in ES6

Tuesday, January 13, 2015

The addition of iterators in ES6 opens up a new world of algorithms and abilities for JavaScript. An iterator is an object that allows code to traverse a sequence of objects. The sequence of objects could be the values inside an array, or values in a more sophisticated data structure like a tree or map. One of the many beautiful characteristics of iterators is how the iterator doesn’t need to know any details about the underlying collection. All an iterator can do is provide the ability to move through a sequence  of items one by one and visit each item inside.

In this post we will look at some of the basic characteristics of an iterator, but a series of future posts will build on this to show both high-level features and some advanced techniques you can use with iterators, or to build your own iterators.

In ES6, array objects will have a few new methods available to work with iterators, and one of these methods is the values method. The values method returns an iterator object that can visit each value in an array.

let sum = 0;
let numbers = [1,2,3,4];

let iterator = numbers.values();
let next = iterator.next();

while(!next.done) {
    sum += next.value;
    next = iterator.next();
}

expect(sum).toBe(10);

An iterator is an object with a next method. Each time the program invokes the next method, the method returns an object with two properties: value and done. The value property represents the next item in the sequence being iterated. The done property is a flag holding the value false if there are more items to iterate through, or the value true if iteration has passed the final item and is complete.

Iterators exist in many other languages, and in some environments, making changes to a sequence during iteration will result in a runtime exception. In JavaScript, changes do not guarantee an error or exception, but you’d still want to exercise caution, because the changes can certainly create confusion. The following code will change the underlying array in the 2nd pass of the while loop. The changes include pushing the value 5 to the end of the array, and unshifting the value 1 to the beginning of the array. The iterator will see the values 1, 2, 2, 3, 4, 5.

let count = 0; 
let sum = 0; 
let numbers = [1,2,3,4]; 

let iterator = numbers.values(); 
let next = iterator.next(); 

while(!next.done) { 
    if(++count == 2) { 
        numbers.push(5); 
        numbers.unshift(1); 
    } 

    sum += next.value; 
    next = iterator.next(); 
} 

expect(sum).toBe(17);

Next up: using iterators the easy way with the new for of.


Comments
gravatar Benjamin Dean Wednesday, January 14, 2015
This is a handy introduction. I look forward to your nect article on the "for of". Thanks
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!