An iterator advances through values one at a time. Calling its next() method returns an iterator result with value and done properties. An iterable is the object that supplies an iterator through Symbol.iterator; the iterator is the object that supplies successive results. section 8.3.1
Listing 8.9 Looping through an array using its iterator
const numbers = [1, 2, 3];
const iterator = numbers[Symbol.iterator](); #A
let iteratorResult = iterator.next(); #B
while (!iteratorResult.done) { #C
console.log(iteratorResult.value); #D
iteratorResult = iterator.next(); #E
}
Calling an array’s iterator directly exposes the repeated next() calls that a for…of loop handles for you. section 8.3.1
Iterators also power destructuring and spread, so these operations can consume iterables beyond arrays. Maps provide iterators for entries, keys, and values. A generator object is both iterable and iterator: each next() call runs until yield or return, and yield pauses execution until the next call. section 8.3.1 section 8.3.2 section 10.2.2
Listing 8.10 Defining a custom iterable
const randomNumbers: Iterable<number> = { #A
[Symbol.iterator]: () => ({ #B
next: () => ({ value: Math.random() }), #B
}), #B
};
const [num1, num2] = randomNumbers; #C
console.log(num1, num2);
This custom iterable uses Symbol.iterator to return an object with a next() method, illustrating the interface beyond built-in collections. section 8.3.1
















