Iterators
The existence of [Symbol.iterator] property in an object makes it iterable.
An iterable object:
- can be looped with the
for-ofloop - can be spread into an array using the
...operator, e.g.[...iterable]
The [Symbol.iterator] property
The [Symbol.iterator] property is a method that when called returns an iterator.
(Note that it is a property that uses Symbol.iterator as its name. Symbol.iterator is a special Symbol defined by JavaScript.)
console.log(Symbol.iterator); //=> Symbol(Symbol.iterator)
console.log(Symbol); //=> <Function: { iterator, ... }>Iterator
An iterator is any object that has the next() method.
const arr = [4, 5, 6, 7];
const iterator = arr[Symbol.iterator]();
console.log(iterator.next); //=> <Function>Iteration result
Calling next() in an iterator returns an iteration result object. An iteration result object is an object containing the following properties:
value(required, any value) — the item being iterated (e.g. the element of an array; key-value pair of a Map).done(required, boolean) —trueif all items have been iterated;falseotherwise.
You can keep calling next until you get iteration result object whose done value is true.
const arr = [4, 5];
const iterator = arr[Symbol.iterator]();
console.log(iterator.next()); //=> { value: 4, done: false }
console.log(iterator.next()); //=> { value: 5, done: false }
console.log(iterator.next()); //=> { value: undefined, done: true }Example: the Range object
class Range {
// `from` and `to` shall be integers
constructor(from, to) {
this.from = from;
this.to = to;
}
// The iterator
// Note that it returns a `{ next }` object
[Symbol.iterator]() {
let nextValue = this.from;
return {
next: () => {
return nextValue <= this.to
? { value: nextValue++, done: false }
: { value: undefined, done: true }
},
}
}
}
// Loops from 2 to 5
for (let x of new Range(2, 5)) {
console.log(x);
}
// `arr` is [ 1, 2, 3, 4 ]
const arr = [...new Range(1, 4)];
console.log(arr);References
- JavaScript: The Definitive Guide, 7th Edition (David Flanagan) — Chapter 12. Iterators and Generators