Sub topic 4
Transforming Values with map
This chapter assumes you know generator functions, for...of, spread syntax, and Array.prototype.map. It also builds on the previous chapter's point that helpers do nothing until a consumer pulls a value.
Iterator.prototype.map(mapper) returns a new iterator. Each value in that iterator is the result of calling mapper on one value from the source iterator. It produces exactly one output for every input, in the same order, and it never skips or adds values. What sets it apart from the array version is when and how that work happens.
The basic shape
map is a method on iterators, not on arrays. To use it on an array, first get an iterator from the array with .values(), .keys(), or .entries().
const doubled = [1, 2, 3].values().map((x) => x * 2);
console.log(doubled.next()); // { value: 2, done: false }
console.log([...doubled]); // [4, 6]
console.log(doubled.next()); // { value: undefined, done: true }The first next() call pulls 1 from the array iterator, passes it to the mapper, and wraps the result as { value: 2, done: false }. The spread then pulls the rest. Once the source reports done: true, the helper reports done: true too, and the mapper never runs again.
The helper is iterable as well as being an iterator. It inherits [Symbol.iterator]() from Iterator.prototype, and that method returns the helper itself, so for...of, spread, Array.from, and destructuring all work on it.
How one value moves through map
Each call to next() on the helper becomes one call to next() on the source, plus one call to the mapper.
The mapper runs between the two next() calls. The helper never asks the source for more than the consumer asked for, so map is safe to use on infinite generators.
Mapping non-array iterators
map pays off most on sources that are already iterators. Calling entries(), keys(), or values() on a Map or Set returns an iterator that inherits from Iterator.prototype. Generators, string iterators, and matchAll results do too.
const prices = new Map([
['apple', 1.2],
['pear', 0.8],
]);
const lines = prices
.entries()
.map(([name, price]) => `${name}: $${price.toFixed(2)}`);
for (const line of lines) {
console.log(line);
}
// apple: $1.20
// pear: $0.80The old way to do this was [...prices.entries()].map(...), which first builds an array of every entry and then a second array of strings. The iterator version builds neither. Each formatted line exists only while the loop body uses it.
Here is a regex example. matchAll returns an iterator of match objects, and map pulls out the part you care about:
const text = 'id=7; id=42; id=1001';
const ids = text
.matchAll(/id=(\d+)/g)
.map((match) => Number(match[1]))
.toArray();
console.log(ids); // [7, 42, 1001]The mapper's arguments
The mapper receives two arguments: the value and a counter that starts at 0 and goes up by one for each value. A later chapter covers the counter. For now, note what the mapper does not receive:
- No third argument.
Array.prototype.mappasses the whole array as the third argument. An iterator has no "whole collection" to pass. - No
thisArg.Iterator.prototype.maptakes one parameter. Any extra argument is silently ignored.
That second point catches people who move array code over unchanged:
const scaler = {
factor: 10,
scale(x) {
return x * this.factor;
},
};
// Array.prototype.map honours thisArg:
console.log([1, 2].map(scaler.scale, scaler)); // [10, 20]
// Iterator.prototype.map ignores it, so bind explicitly or use an arrow:
const viaBind = [1, 2].values().map(scaler.scale.bind(scaler)).toArray();
const viaArrow = [1, 2].values().map((x) => scaler.scale(x)).toArray();
console.log(viaBind, viaArrow); // [10, 20] [10, 20]Comparison with Array.prototype.map
| Aspect | `Array.prototype.map` | `Iterator.prototype.map` |
|---|---|---|
| When the mapper runs | Immediately, for every element | One call per `next()`, only when pulled |
| Return value | A new array | A new iterator (an iterator helper) |
| Mapper arguments | `(value, index, array)` | `(value, counter)` |
| `thisArg` parameter | Yes | No |
| Memory for results | Holds every result at once | Holds one result at a time |
| Reusable result | Yes, arrays can be read many times | No, the helper is consumed once |
| Works on infinite input | No | Yes |
| Holes in sparse arrays | Skipped, kept as holes | Not applicable; `values()` yields `undefined` for holes |
The last row matters if your data is sparse. [1, , 3].map(f) calls f twice. [1, , 3].values().map(f) calls it three times, with undefined as the middle value.
What the mapper returns is what you get
map does not inspect or flatten what the mapper returns. If the mapper returns undefined, the helper yields undefined. If it returns an array, you get an array as a single value, not its elements. Splitting one input into several outputs is flatMap's job, covered later.
Async mappers follow the same rule. The helper yields promises and does not await them:
const pending = ['a', 'b', 'c']
.values()
.map(async (s) => s.toUpperCase());
Promise.all(pending).then((values) => {
console.log(values); // ['A', 'B', 'C']
});This works because Promise.all accepts any iterable. Keep in mind that every mapper call starts when Promise.all pulls the value, so all three async operations run at the same time. Iterator helpers do not limit or order async work. Async iterator helpers are a separate proposal and are not part of ES2025.
Errors inside and around map
There are two kinds of failure, and they surface at different times.
A non-callable mapper fails immediately. map checks its argument when you call it, before any value is pulled:
try {
[1, 2, 3].values().map('not a function');
} catch (e) {
console.log(e instanceof TypeError); // true
}A mapper that throws closes the source. If the mapper throws during a pull, the helper calls return() on the source iterator before rethrowing. A generator's finally block therefore runs before your catch sees the error:
function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('source closed');
}
}
const it = source().map((x) => {
if (x === 2) throw new Error('bad value');
return x * 10;
});
console.log(it.next().value); // 10
try {
it.next();
} catch (e) {
console.log(e.message);
}
// source closed
// bad valueAfter that, the helper is finished. Further next() calls return { value: undefined, done: true }, and the source is never resumed. If the source throws from its own next(), the helper passes the error through without closing the source, because a source that threw is already considered broken.
Common mistakes
- Calling
.mapon an array and expecting an iterator.[1, 2].map(f)is still the eager array method. Write[1, 2].values().map(f)to get the lazy one. - Expecting results without consuming.
source().map(f)with nothing pulling from it never callsf. - Spreading the same helper twice. The second spread is empty because the helper is single-use.
- Passing
thisArg. It is ignored, as shown above.
Exercise
What does this code log, and in what order? function* g() { try { yield 'a'; yield 'b'; } finally { console.log('done'); } } const m = g().map((s, i) => s + i); console.log(m.next().value); console.log(m.return()); console.log(m.next());
Show answer
It logs a0, then done, then { value: undefined, done: true } twice. The first pull maps 'a' with counter 0. Calling return() on the helper closes the generator, so its finally block logs done before return() hands back its result. Once closed, the helper reports done on every later next(), and 'b' is never produced.
Exercise
You have const users = new Map([[1, { name: 'Ana' }], [2, { name: 'Bo' }]]);. Write one expression that produces the array ['1:Ana', '2:Bo'] without first building an array of entries, and explain why [...users.entries()].map(...) uses more memory.
Show answer
users.entries().map(([id, u]) => ${id}:${u.name}).toArray(). The map helper pulls one entry at a time and toArray collects only the final strings. The spread version first copies every [key, value] pair into an array, then Array.prototype.map allocates a second array, so both arrays are in memory at the same time.
Exercise
Why does [1, 2, 3].values().map(null) throw right away, while [1, 2, 3].values().map((x) => x.foo.bar) throws only on the first next() call?
Show answer
map validates its argument when it is called. null is not callable, so it throws a TypeError right away. The arrow function is a valid callable, so creating the helper succeeds. The mapper runs only when a value is pulled, and that is when reading .bar of undefined throws.