An iterable supplies a method at Symbol.iterator. Calling that method produces an iterator with next(), whose result is an object containing value and done. for/of uses this protocol for you. An array is iterable; the iterator created from it holds a current position.
Symbols are unique property keys. Symbol.iterator is a shared well-known symbol that JavaScript recognizes as a protocol hook. It does not mean an ordinary property named "iterator". You will usually write generators rather than implement the protocol by hand, but the pool in this course calls next() and return() itself, so this lesson writes one iterator out in full.
Two iterators from one array progress independently. One iterator can be exhausted and then keeps reporting done. An iterable is not necessarily reusable: a generator object is itself a stateful iterator, so iterating it again does not restart it.
The task pool will accept a synchronous iterable and pull values only when a worker slot is available. This makes demand visible, but returning every result still requires memory proportional to the number of results.
Predict, run, and explain
Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.
const values = [10, 20];
const first = values[Symbol.iterator]();
const second = values[Symbol.iterator]();
console.log(first.next().value);
console.log(first.next().value);
console.log(second.next().value);
console.log(first.next().done);Check your prediction
10
20
10
trueOne iterable can produce independent cursors
Iterable and iterator are roles, not interchangeable names for a collection. The iterable can create an iterator; the iterator tracks progress and returns result records. A next result describes both whether a value was produced and whether iteration has finished.
An iterator may be the iterable itself, as with a generator object, so a second loop can find it already exhausted. Reuse requires creating a fresh iterator or calling the generator function again, not merely putting the same stateful object in another for-of loop.
const values = ["a", "b"];
const cursor = values[Symbol.iterator]();
console.log(cursor.next().done);
console.log(cursor.next().value);
console.log(cursor.next().done);
console.log(cursor.next().done);Check your prediction
false
b
true
trueThe first call consumed a even though it only printed done. Reading one field of the result does not undo the advancement.
const values = ["a", "b"];
const a = values[Symbol.iterator]();
const b = values[Symbol.iterator]();
a.next();
console.log(a.next().value);
console.log(b.next().value);Check your prediction
b
aEach iterator owns its position. The array data is shared, but the cursors are not one shared progress counter.
Try the rule on new inputs
Collect every next result for an empty and a one-item array. Mark which call consumes a value. Then explain why collecting all results from an infinite iterable cannot finish.
Write the protocol by hand
Generators write most of this for you, but the task pool and its tests talk to iterators directly, so it is worth seeing every piece once. An iterable is any object with a [Symbol.iterator]() method; that method returns an iterator, an object with next() and, optionally, return(). Each next() returns { value, done }. Predict both log lines.
function range(start, end, log) {
return {
[Symbol.iterator]() {
let current = start;
return {
next() {
if (current >= end) {
log.push("done");
return { value: undefined, done: true };
}
log.push(`next ${current}`);
return { value: current++, done: false };
},
return() {
log.push("return");
return { value: undefined, done: true };
}
};
}
};
}
const full = [];
for (const n of range(1, 3, full)) {
full.push(`body ${n}`);
}
console.log(full.join(", "));
const early = [];
for (const n of range(1, 9, early)) {
early.push(`body ${n}`);
if (n === 2) break;
}
console.log(early.join(", "));Check your prediction
next 1, body 1, next 2, body 2, done
next 1, body 1, next 2, body 2, returnA complete loop calls next until it reports done: true and never calls return: there is nothing to clean up because the iterator finished on its own. Leaving early with break makes for...of call return() exactly once, so the iterator can release whatever it holds. (The same happens when the loop body throws or a function returns from inside the loop.) return is optional in the protocol, which is why consumers you write by hand call it as iterator.return?.().
Trace the contract before building
An iterable and an iterator have different responsibilities. The iterable supplies a cursor; the iterator's next method advances that cursor. Two fresh array cursors can move independently, while repeatedly using an exhausted generator object does not restart its body.
Trace both value and done in each next result, including the final completion. The last yielded value and the done result are separate steps. A consumer that manually pulls values also takes responsibility for stopping demand and closing unfinished iteration when its policy requires it. A for/of loop performs parts of that protocol on your behalf.
Your turn
An iterable that cleans up once
Write words(text, onClose) by hand, without a generator. It returns an iterable over the space-separated words of text (ignoring empty pieces). Each call to [Symbol.iterator]() starts a fresh cursor. Its iterator's return() calls onClose the first time only, and after return() the iterator reports done: true for good. Spread it, leave a for...of early, and drive one cursor by hand. Print:
pull|values|on|demand 0
1
pull
true 2function words(text, onClose) {
// Return { [Symbol.iterator]() { ... } } with next() and return().
return [];
}
let closes = 0;
const source = words(" pull values on demand ", () => {
closes += 1;
});
console.log([...source].join("|"), closes);Hint 1: the idea
There are two kinds of state: the words themselves, which belong to the iterable, and the position plus a "closed" flag, which belong to each iterator. Only the second kind should be created inside [Symbol.iterator](). Count when onClose runs: a finished spread is not a close.
Hint 2: a first step
Start with [Symbol.iterator]() returning an object with only next(), reading from parts with an index. Run: the spread prints the four words and 0. Then add return() and check that the break makes closes become 1.
Show one solution
function words(text, onClose) {
return {
[Symbol.iterator]() {
const parts = text.split(" ").filter(part => part !== "");
let index = 0;
let closed = false;
return {
next() {
if (closed || index >= parts.length) {
return { value: undefined, done: true };
}
return { value: parts[index++], done: false };
},
return() {
if (!closed) {
closed = true;
onClose();
}
return { value: undefined, done: true };
}
};
}
};
}
let closes = 0;
const onClose = () => {
closes += 1;
};
const source = words(" pull values on demand ", onClose);
console.log([...source].join("|"), closes);
for (const word of source) {
if (word === "values") break;
}
console.log(closes);
const manual = source[Symbol.iterator]();
console.log(manual.next().value);
manual.return();
manual.return();
console.log(manual.next().done, closes);pull|values|on|demand 0
1
pull
true 2The spread ran next until done and never called return, so closes is still 0. The break made for...of call return() once: 1. The manual cursor shows the two guarantees the brief adds on top of the protocol: the closed flag makes a second return() harmless (still 2, not 3), and next() after closing reports done instead of resuming at "values". Because parts, index and closed are created inside [Symbol.iterator](), the spread, the loop and the manual cursor each start at "pull". Creating them once in words would make the second loop find an exhausted iterator.
Change it and test it
Inspect Object.keys(values) and explain why it does not show Symbol.iterator. Test an empty list. Then write down why an infinite iterable would be unsuitable for a helper that collects all results before returning.
Completion is saved in this browser only. It does not measure mastery.