This article is in need of a technical review.
This article is in need of an editorial review.
This is an experimental technology, part of the Harmony (ECMAScript 6) proposal.
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.
One addition of ECMAScript 6 is not new syntax or a new built-in, but a protocol. This protocol can be implemented by any object respecting some conventions.
Description
An iterator has a method called next
. This method returns an object with two properties: value
(any value) and done
(will be read as a boolean).
Examples
Simple iterator
function makeIterator(array){ var nextIndex = 0; return { next: function(){ return nextIndex < array.length ? {value: array[nextIndex++], done: false} : {done: true}; } } } var it = makeIterator(['yo', 'ya']); console.log(it.next().value); // 'yo' console.log(it.next().value); // 'ya' console.log(it.next().done); // true
Infinite iterator
function idMaker(){ var index = 0; return { next: function(){ return {value: index++, done: false}; } } } var it = idMaker(); console.log(it.next().value); // '0' console.log(it.next().value); // '1' console.log(it.next().value); // '2' // ...
With a generator
function* makeSimpleGenerator(array){ var nextIndex = 0; while(nextIndex < array.length){ yield array[nextIndex++]; } } var gen = makeSimpleGenerator(['yo', 'ya']); console.log(gen.next().value); // 'yo' console.log(gen.next().value); // 'ya' console.log(gen.next().done); // true function* idMaker(){ var index = 0; while(true) yield index++; } var gen = idMaker(); console.log(gen.next().value); // '0' console.log(gen.next().value); // '1' console.log(gen.next().value); // '2' // ...
For more informations on ES6 generators, see the dedicated page.
The deprecated Firefox-only iterator protocol
Firefox, prior to version 26 implemented another iterator protocol. The value was returned directly as a return value of calls to next
(instead of the value
property of a placeholder object). Iteration termination was expressed by throwing a StopIteration
object. This version of the protocol has been removed.
Simple example with the old protocol
function makeIterator(array){ var nextIndex = 0; return { next: function(){ if(nextIndex < array.length){ return array[nextIndex++]; else throw new StopIteration(); } } } var it = makeIterator(['yo', 'ya']); console.log(it.next()); // 'yo' console.log(it.next()); // 'ya' try{ console.log(it.next()); } catch(e){ if(e instanceof StopIteration){ // iteration over } }