Sub topic 12
Pitfalls: Single-Use Iterators and Arrays That Are Not Iterators
This chapter covers the two mistakes people make most often when they start using iterator helpers. The first is reading an iterator twice. The second is calling a helper on an array as if the array were an iterator. Both mistakes fail quietly or with a confusing error, so you should learn to spot them early.
The chapter assumes you know arrow functions, spread syntax, for...of loops, generator functions, and the lazy map, filter, take, and drop helpers from earlier chapters.
An Iterator Is a Cursor
An iterator holds a position in a sequence. Each call to next() moves that position forward, and the position never moves back. Once next() returns { done: true }, the iterator is exhausted and stays exhausted.
Every helper result is an iterator too, so a pipeline built from helpers can be read only once:
const evens = [1, 2, 3, 4].values().filter((n) => n % 2 === 0);
console.log([...evens]); // [2, 4]
console.log([...evens]); // []The second spread throws no error. It finds an iterator that has nothing left and returns an empty array. This silent failure makes the bug hard to find: the code runs, and the data is gone.
Why `for...of` does not restart it
Iterators are also iterables. Their [Symbol.iterator]() method returns the iterator itself, not a new one. When for...of or spread asks an iterator for an iterator, it gets the same cursor back at its current position. Arrays behave differently. array[Symbol.iterator]() builds a new iterator each time, which is why you can loop over an array as many times as you like.
const it = [1, 2, 3].values();
console.log(it[Symbol.iterator]() === it); // true
const arr = [1, 2, 3];
console.log(arr[Symbol.iterator]() === arr[Symbol.iterator]()); // falseThe hidden second read
The obvious case is spreading the same variable twice. A subtler case is passing a pipeline to code that reads its input more than once:
const doubled = [3, 8, 1, 6].values().map((x) => x * 2);
const max = Math.max(...doubled);
const min = Math.min(...doubled);
console.log(max); // 16
console.log(min); // InfinityMath.min() with no arguments returns Infinity, so the bug shows up as a strange number and you get no error. Watch for the same issue in helper functions that loop twice, for example one pass to count and a second pass to process.
Shared sources interleave
Helpers do not copy their source. Two pipelines built on the same underlying iterator both pull from that one cursor:
const src = [1, 2, 3, 4, 5, 6].values();
const tens = src.map((x) => x * 10);
const evens = src.filter((x) => x % 2 === 0);
console.log(tens.next().value); // 10 (src gave 1)
console.log(evens.next().value); // 2 (src gave 2)
console.log(tens.next().value); // 30 (src gave 3)Neither pipeline sees the whole sequence. If you need two independent views, create two sources.
Partial consumption leaves the cursor where it stopped
If you read part of an iterator and then hand it on, the next reader starts where you stopped:
const it = [1, 2, 3, 4, 5].values();
for (const n of it) {
if (n === 2) break;
}
console.log([...it]); // [3, 4, 5]Sometimes this is exactly what you want, for example when you read a header row and then process the body. But it is a different result from calling slice(2) on an array, and it depends on the source. Generators have a return() method that break calls, so a generator stops for good after an early exit. Array iterators have no return() method, so they keep their position. The chapter on early termination covers that difference in detail.
The Fix: Make Pipelines From a Factory
Do not store a pipeline in a variable and reuse it. Store a function that builds a fresh one:
const numbers = [3, 8, 1, 6];
const doubled = () => numbers.values().map((x) => x * 2);
console.log(Math.max(...doubled())); // 16
console.log(Math.min(...doubled())); // 2Generator functions work the same way. Each call to naturals() returns a new generator object starting at zero, so call the function again and do not reuse the object.
If the source can be read only once (for example a network stream wrapped as an iterator) and you need to read the data several times, use toArray() once and work from the array.
Arrays Are Iterables, Not Iterators
An array is iterable: it has a [Symbol.iterator] method. It is not an iterator, and it does not inherit from Iterator.prototype. So helper methods such as take and drop do not exist on arrays:
try {
[1, 2, 3].take(2);
} catch (e) {
console.log(e instanceof TypeError); // true
}The worse case: `map` and `filter` exist on both
Array.prototype has its own map and filter, so calling them on an array runs without error. They run the eager array versions: every element is processed immediately and a new array is allocated. The error shows up later, at the first helper that arrays lack:
const words = ['apple', 'banana', 'cherry', 'date'];
try {
words.map((w) => w.toUpperCase()).take(2);
} catch (e) {
console.log(e.message.includes('take')); // true
}The fix is to get an iterator first with .values():
const words = ['apple', 'banana', 'cherry', 'date'];
const firstTwo = words
.values()
.map((w) => w.toUpperCase())
.take(2)
.toArray();
console.log(firstTwo); // ['APPLE', 'BANANA']Here toUpperCase runs only twice. In the eager version it would run four times before take was even reached.
Helper results are not arrays either
The pitfall also works in the other direction. A helper returns an iterator, and an iterator has no length, no index access, and no array methods such as includes or join:
const it = [1, 2, 3].values().map((x) => x + 1);
console.log(it.length); // undefined
console.log(it[0]); // undefined
console.log(typeof it.join); // 'undefined'
console.log(it.toArray().join(',')); // '2,3,4'If the next step needs array features, end the pipeline with toArray().
Getting an Iterator From Common Sources
| Source | How to get an iterator | What it yields |
|---|---|---|
| Array | `arr.values()` | elements |
| Array with indexes | `arr.entries()` | `[index, element]` pairs |
| Set | `set.values()` | members |
| Map | `map.entries()` | `[key, value]` pairs |
| Map values only | `map.values()` | values |
| String | `str[Symbol.iterator]()` | code points |
| Plain object | `Object.entries(obj).values()` | `[key, value]` pairs |
| Generator function | call it: `gen()` | yielded values |
Map and Set iterators, string iterators, and generator objects all inherit from Iterator.prototype, so helpers work on them directly. For any other iterable, Iterator.from(iterable) returns a helper-capable iterator. A later chapter covers it.
A Quick Checklist
- Does this variable hold an iterator? Then read it once, or make it with a factory function.
- Does any function you pass it to read its input twice? Then pass an array or a fresh iterator.
- Are two pipelines built on the same source? They will split its values between them.
- Does the chain start from an array? Insert
.values()before the first helper. - Does the next step need
length, indexing, orjoin? End the pipeline withtoArray().
Exercise
This code is meant to log the number of active users and then their names, but the second line logs an empty array. Explain why and fix it so each step reads the data correctly while staying lazy. const active = users.values().filter((u) => u.active); console.log(active.reduce((n) => n + 1, 0)); console.log(active.map((u) => u.name).toArray());
Show answer
active is a single iterator. reduce consumes it completely to count, so the later map(...).toArray() pulls from an exhausted iterator and gets []. Build the pipeline from a factory: const active = () => users.values().filter((u) => u.active); then call active().reduce((n) => n + 1, 0) and active().map((u) => u.name).toArray(). Each call creates a fresh iterator over the array.
Exercise
What does [10, 20, 30, 40].filter((n) => n > 15).drop(1) do, and how would you rewrite it to return [30, 40] using iterator helpers?
Show answer
Array.prototype.filter runs eagerly and returns the array [20, 30, 40]. Arrays have no drop method, so the call throws a TypeError. Rewrite it as [10, 20, 30, 40].values().filter((n) => n > 15).drop(1).toArray(), which returns [30, 40].
Exercise
Given const src = [1, 2, 3, 4].values(); const a = src.map((x) => x * 2); const b = src.take(2);, what does [...b] followed by [...a] log?
Show answer
[...b] pulls 1 and 2 from the shared source and logs [1, 2]. When take reaches its limit it tries to close the source, but array iterators have no return() method, so the source keeps its position. [...a] then pulls 3 and 4 and logs [6, 8].