Javascript Iterators and Iterables

The EcmaScript2015 standard specifies Javascript iterators and iterables. These specifications are protocols rather than builtins or syntax. You can implement the protocols in any object just by respecting some conventions.

Iterators:

Iterators are objects that know how to access items in a collection while keeping track of its current position in the collection. The object will have a next() method that returns the next item in the sequence as values and a boolean done flag. If the done field is true, the value field can be omitted and should be ignored.

Iterables:

Iterables are objects that implement the @@iterator method. This signature is available as Symbol.iterator. The @@iterator method must take zero arguments and returns an iterator object, as defined above.

Some iterators are also iterables.

Here is some sample code of iterables:
var myString = "do it";
console.log( typeof( myString[Symbol.iterator]) );

var iterator = myString[Symbol.iterator]();
console.log( iterator + '' ); // "[object String Iterator]"

console.log(iterator.next()); // { value: "d", done: false }
console.log(iterator.next()); // { value: "0", done: false }
console.log(iterator.next()); // { value: " ", done: false }
console.log(iterator.next()); // { value: "i", done: false }
console.log(iterator.next()); // { value: "t", done: false }
console.log(iterator.next()); // { value: undefined, done: true }

console.log( [...myString] ); // spread operator
console.log( "=======");

var myArray = [1, 2, 3, 4, 5];
console.log( typeof( myArray[Symbol.iterator]) );

var Aiterator = myArray[Symbol.iterator]();
console.log( Aiterator + '' ); // "[object String Iterator]"

console.log(Aiterator.next()); // { value: "d", done: false }
console.log(Aiterator.next()); // { value: "0", done: false }
console.log(Aiterator.next()); // { value: " ", done: false }
console.log(Aiterator.next()); // { value: "i", done: false }
console.log(Aiterator.next()); // { value: "t", done: false }
console.log(Aiterator.next()); // { value: undefined, done: true }

console.log( [...myArray] ); // spread operator

Some of my posts will detail patterns and functionalities that call for iterables.

This entry was posted in Articles, Technology. Bookmark the permalink.