Sub topic 1
Iterables and Iterators: A Quick Refresher
Iterator helpers such as map, filter, take, and drop are methods on iterators, not on arrays. Before using them, you need a clear picture of what an iterator is, how it differs from an iterable, and which language features consume them. This chapter rebuilds that picture from the protocol up.
Prerequisites
This chapter assumes you are comfortable with:
- Modern JavaScript syntax: arrow functions,
constandlet, and the spread operator (...) - Array methods such as
mapandfilter for...ofloops- Generator functions declared with
function*and theyieldkeyword
You do not need to know how Symbol.iterator works internally. This chapter covers it.
Two Protocols, Not One
JavaScript defines iteration through two separate contracts. People often treat them as one, and that habit leads to bugs later.
- The iterable protocol says that an object is iterable if it has a method under the key
Symbol.iterator, and that this method returns an iterator. - The iterator protocol says that an object is an iterator if it has a
next()method, and each call tonext()returns an iterator result: an object with avalueproperty and a booleandoneproperty.
An iterable is a source you can ask for a fresh traversal. An iterator is one traversal in progress, with its own position. An array is iterable but is not an iterator: it has no next() method. When you call array[Symbol.iterator](), you get a separate iterator object that tracks where it is in that array.
| Concept | Required member | Returns | Example |
|---|---|---|---|
| Iterable | `[Symbol.iterator]()` | An iterator | Array, String, Map, Set |
| Iterator | `next()` | `{ value, done }` | `[1, 2][Symbol.iterator]()` |
| Iterator (optional) | `return(value)` | `{ value, done: true }` | Generator objects |
| Iterator (optional) | `throw(error)` | An iterator result, or throws | Generator objects |
Driving an Iterator by Hand
for...of hides the protocol. Calling next() yourself shows what happens underneath:
const letters = ['a', 'b'];
const it = letters[Symbol.iterator]();
console.log(it.next()); // { value: 'a', done: false }
console.log(it.next()); // { value: 'b', done: false }
console.log(it.next()); // { value: undefined, done: true }
console.log(it.next()); // { value: undefined, done: true }Once an iterator reports done: true, further calls keep returning done: true. Nothing rewinds it. To start again you must ask the iterable for a new iterator.
The diagram below shows the same exchange as for...of performs it.
Writing an Iterable by Hand
Implementing both protocols yourself makes the split concrete. This range object is iterable. Its Symbol.iterator method returns a new iterator each time it is called:
const range = {
from: 1,
to: 3,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
return current <= last
? { value: current++, done: false }
: { value: undefined, done: true };
},
};
},
};
console.log([...range]); // [1, 2, 3]
console.log([...range]); // [1, 2, 3] (a fresh iterator each time)
for (const n of range) {
console.log(n); // 1, then 2, then 3
}Because range creates new state on every call, you can spread it any number of times. A single iterator object does not have that property, as the next section shows.
Generators: Iterator and Iterable at Once
A generator function returns a generator object. That object is an iterator, because it has next(), return(), and throw(). It is also iterable, because its Symbol.iterator method returns the object itself:
function* countTo(limit) {
for (let i = 1; i <= limit; i++) {
yield i;
}
return 'finished';
}
const gen = countTo(2);
console.log(gen[Symbol.iterator]() === gen); // true
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 'finished', done: true }
console.log([...countTo(2)]); // [1, 2]Two details matter here:
- The
returnvalue of a generator appears only on the final result, alongsidedone: true. Spread,for...of, andArray.fromall ignore it, which is why[...countTo(2)]does not include'finished'. - Because the generator returns itself from
Symbol.iterator, spreading the same generator object twice gives the values once and then an empty array. The traversal state belongs to the object, and the object is spent after one pass.
Who Consumes Iterables
Many language features accept any iterable and drive the protocol for you. Each one calls Symbol.iterator, then calls next() until done is true or it stops early.
| Feature | Example | Stops early? |
|---|---|---|
| `for...of` | `for (const x of src) {}` | Yes, on `break`, `return`, or a thrown error |
| Spread | `[...src]`, `fn(...src)` | No |
| `Array.from` | `Array.from(src)` | No |
| Array destructuring | `const [a, b] = src` | Yes, after the needed elements |
| Collection constructors | `new Set(src)`, `new Map(src)` | No |
| Delegation | `yield* src` | Follows the outer consumer |
| Promise combinators | `Promise.all(src)` | No |
The "stops early" column matters. When a consumer stops before done: true, it calls the iterator's optional return() method so the source can clean up. Destructuring shows this clearly:
function* letters() {
try {
yield 'a';
yield 'b';
yield 'c';
} finally {
console.log('closed');
}
}
const [first] = letters();
// closed
console.log(first); // 'a'Destructuring needed one value, so it called return() on the generator, and that ran the finally block. A later chapter covers how take uses the same mechanism.
Built-in Iterables and Their Iterators
Most collections in the language are iterable, and many give you more than one kind of iterator:
- Array:
values()(the default),keys(),entries() - String: iterates by code point, so
[...'👍a']has two elements, not three - Map:
entries()(the default),keys(),values() - Set:
values()(the default),keys(),entries() arguments, typed arrays, and DOM collections such asNodeList
Each of these methods returns an iterator, not an array:
const scores = new Map([
['ana', 9],
['ben', 7],
]);
const names = scores.keys();
console.log(typeof names.next); // 'function'
console.log(Array.isArray(names)); // false
console.log([...names]); // ['ana', 'ben']This difference is the reason iterator helpers exist. scores.keys() has no array map method, so before ES2025 you had to spread it into an array first just to transform it. The iterators returned by built-in methods and by generators share a common prototype, and that shared prototype is where the helpers are attached. The next chapter looks at it.
Exercises
Exercise
An object has a next() method that returns correct { value, done } results, but no Symbol.iterator method. Can you use it in for...of? Explain which protocol it satisfies.
Show answer
No. It satisfies the iterator protocol but not the iterable protocol. for...of starts by calling [Symbol.iterator]() on its operand, and because that method is missing it throws a TypeError. Adding [Symbol.iterator]() { return this; } makes the object iterable.
Exercise
What does this code log, and why? function* g() { yield 1; return 2; } const it = g(); console.log([...it]); console.log([...it]);
Show answer
It logs [1] and then []. Spread ignores the value 2 because that value arrives with done: true. The generator object returns itself from Symbol.iterator, so the second spread resumes the same finished iterator, which reports done: true straight away.
Exercise
You write const [a] = someGenerator(); and the generator has a finally block. Does the finally block run, even though the generator never reached its end?
Show answer
Yes. Array destructuring stops after taking the elements it needs and then calls the iterator's return() method. On a generator, return() resumes it as if a return statement ran at the paused yield, so the finally block executes.