Loading lessons...
Iterables and Iterators
Iterables and Iterators
Iterables are data structures you can loop through with for...of.
Common iterables
- Arrays
- Strings
- Sets
- Maps
- NodeLists
for (let item of ["a", "b"]) {
console.log(item);
}
What makes something iterable?
An iterable has a special method called Symbol.iterator. The for...of loop uses it behind the scenes.
Iterators
An iterator is an object that walks through an iterable one step at a time. It has a next() method that returns:
{ value: ... , done: false } // more items to come
{ value: ..., done: true } // finished
Manual iteration
const it = [10, 20][Symbol.iterator]();
it.next(); // { value: 10, done: false }
it.next(); // { value: 20, done: false }
it.next(); // { value: undefined, done: true }
TL;DR
- Iterables are things you can loop with for...of.
- Arrays, strings, Sets, and Maps are iterable.
- Iterators have a next() method.
- next() returns { value, done }.