Sub topic 4
map: Transforming Every Element
This chapter assumes you can write arrow functions and that you know what a callback is. It also assumes you know that map passes each callback three arguments: the element, the index, and the array. Earlier chapters covered those ideas. Here the focus is on map itself: what it does step by step, what it returns, and the edge cases that cause bugs in real code.
The Contract of map
map calls a function once for each element of an array and collects the return values into a new array. The new array always has the same length as the original. The value at position i in the result is whatever your callback returned for position i in the source.
const names = ['ada', 'grace', 'linus'];
const capitalized = names.map(name => name[0].toUpperCase() + name.slice(1));
console.log(capitalized); // ['Ada', 'Grace', 'Linus']
console.log(names); // ['ada', 'grace', 'linus'] (original unchanged)The full signature is array.map(callbackFn, thisArg):
| Part | Meaning |
|---|---|
| `callbackFn(element, index, array)` | Called once per present element. Its return value becomes the matching element of the result. |
| `thisArg` (optional) | The value of `this` inside `callbackFn`. It has no effect on arrow functions. |
| Return value | A new array with the same length as the source. |
| Effect on the source | `map` does not change the source, but your callback can. |
The contract leaves two decisions to you. You decide what each element turns into. You also decide whether the callback has side effects, and it should not have any.
A Working Model: map Written by Hand
You can predict map's behavior in every edge case below by writing a simplified version yourself. This version follows the steps the ECMAScript specification describes, minus the subclassing details:
function myMap(array, callback, thisArg) {
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
const len = array.length; // length is read once, up front
const result = new Array(len); // result has the same length
for (let i = 0; i < len; i++) {
if (i in array) { // holes are skipped
result[i] = callback.call(thisArg, array[i], i, array);
}
}
return result;
}
console.log(myMap([1, 2, 3], n => n * 2)); // [2, 4, 6]Three details in this sketch explain most of map's surprising behavior:
- The length is read once, before the loop starts.
- Indexes that hold no value at all (holes) are never passed to the callback.
- The callback's return value is stored without any checks, so
undefinedis stored like any other value.
Edge Case: The Length Is Fixed at the Start
Because map captures the length before it starts, elements added during iteration are never visited:
const arr = [1, 2, 3];
const out = arr.map((n, i, a) => {
if (i === 0) a.push(99); // mutating the source during map: don't do this
return n * 10;
});
console.log(out); // [10, 20, 30]
console.log(arr); // [1, 2, 3, 99]Elements that were deleted or changed before map reaches them work differently. map reads each element at the moment it visits that index, so it sees the current value. If you ever have to reason through this, the code has a design problem. Treat the source array as read-only while map runs.
Edge Case: Holes Stay Holes
A sparse array has indexes with no value at all, which is different from holding undefined. map skips the holes and keeps them in the result:
const sparse = [1, , 3];
const doubled = sparse.map(n => n * 2);
console.log(doubled); // [2, <1 empty item>, 6] in Node
console.log(1 in doubled); // false
console.log([1, undefined, 3].map(n => n * 2)); // [2, NaN, 6]The callback ran twice for the sparse array and three times for the array holding undefined. The pitfalls chapter covers sparse arrays in more detail. For now, remember that "same length" does not always mean "same number of callback calls."
Bug Source: The Callback Must Return
Whatever the callback returns goes into the result. If it returns nothing, the result element is undefined. This happens most often when an arrow function body gets braces and loses its implicit return:
const broken = [1, 2, 3].map(n => { n * 2; });
console.log(broken); // [undefined, undefined, undefined]
const fixedExpression = [1, 2, 3].map(n => n * 2);
const fixedBlock = [1, 2, 3].map(n => {
const doubled = n * 2;
return doubled;
});
console.log(fixedExpression, fixedBlock); // [2, 4, 6] [2, 4, 6]A related trap catches people when they return object literals. JavaScript reads { right after => as the start of a function body, not as an object:
const wrong = [1, 2].map(n => { value: n });
console.log(wrong); // [undefined, undefined]
const right = [1, 2].map(n => ({ value: n }));
console.log(right); // [{ value: 1 }, { value: 2 }]In the wrong version, value: is parsed as a statement label and n as an expression statement, so the function returns nothing. Wrapping the object in parentheses makes it an expression.
Mapping to Different Shapes
The result keeps the source's length, but its elements do not need the source's type. Common transformations include:
- Extracting a field (projection):
users.map(u => u.email) - Building view models:
users.map(u => ({ id: u.id, label:${u.first} ${u.last}})) - Using the index:
items.map((item, i) =>${i + 1}. ${item}) - Producing pairs for later conversion:
keys.map(k => [k, defaults[k]])
const users = [
{ id: 7, first: 'Ada', last: 'Lovelace', email: '[email protected]' },
{ id: 9, first: 'Alan', last: 'Turing', email: '[email protected]' }
];
const options = users.map(u => ({ value: u.id, label: `${u.first} ${u.last}` }));
const numbered = users.map((u, i) => `${i + 1}. ${u.last}`);
console.log(options); // [{ value: 7, label: 'Ada Lovelace' }, { value: 9, label: 'Alan Turing' }]
console.log(numbered); // ['1. Lovelace', '2. Turing']If you need fewer elements than you started with, map is the wrong tool. Returning null for the elements you don't want leaves those null values in the result. Use filter (next chapter) for that, or flatMap when one element can become zero or several.
Passing Named Functions and thisArg
You can pass any function, not only an inline arrow. Named functions make a pipeline easier to read:
const toCelsius = f => Math.round(((f - 32) * 5) / 9);
console.log([32, 212, 98.6].map(toCelsius)); // [0, 100, 37]Make sure the function expects exactly what map passes it. Every callback receives three arguments, and a function with optional extra parameters can misread the index. The map(parseInt) case in the pitfalls chapter is the classic example.
Passing a method by reference loses its this. The second argument to map restores it:
const converter = {
rate: 1.5,
convert(amount) {
return amount * this.rate;
}
};
console.log([10, 20].map(converter.convert, converter)); // [15, 30]
console.log([10, 20].map(a => converter.convert(a))); // [15, 30]Without converter as the second argument, this would be undefined in strict mode, and calling the method would throw a TypeError. Most modern code uses the arrow-function wrapper because it is clearer, but you will see thisArg in older codebases.
map on Things That Aren't Arrays
Array-like objects and strings
map is generic. It needs only a length property and indexed elements. Two ways to use it on array-like values:
const upper = Array.prototype.map.call('abc', c => c.toUpperCase());
console.log(upper); // ['A', 'B', 'C']
const squares = Array.from({ length: 4 }, (_, i) => i * i);
console.log(squares); // [0, 1, 4, 9]Array.from(source, mapFn) builds an array and maps it in a single pass. It works for any iterable (a Set, a Map, a NodeList) and for array-likes. Unlike map, it treats missing indexes as undefined instead of holes.
Typed arrays keep their type
map on a typed array returns a typed array of the same kind. Values that don't fit get converted to fit, with no error:
const bytes = new Uint8Array([200, 100]);
console.log(bytes.map(n => n * 2)); // Uint8Array(2) [144, 200]
console.log(Array.from(bytes, n => n * 2)); // [400, 200]The 400 wrapped around to 144 (400 minus 256). To get unrestricted numbers, convert to a regular array with Array.from first.
map Versus forEach Versus a Loop
| Tool | Returns | Use it when |
|---|---|---|
| `map` | A new array of the same length | You want a transformed copy |
| `forEach` | `undefined` | You want side effects only (logging, writing to the DOM) |
| `for...of` | Nothing | You need `break`, `await` in sequence, or full control |
Calling map and ignoring its result is a code smell. It allocates an array nobody uses, and it tells the reader a transformation happens when none does. Use forEach or a loop for side effects.
Exercises
Exercise
What does [1, 2, 3].map(n => { if (n > 1) return n * 10; }) return, and why?
Show answer
It returns [undefined, 20, 30]. For n = 1 the callback reaches the end of its body without returning, so it returns undefined, and map stores that value at index 0. map never drops elements. To remove the first element you would use filter before map.
Exercise
Given const products = [{ name: 'pen', cents: 150 }, { name: 'ink', cents: 999 }], write one map call that returns [{ name: 'pen', price: '$1.50' }, { name: 'ink', price: '$9.99' }] without changing products.
Show answer
products.map(p => ({ name: p.name, price: $${(p.cents / 100).toFixed(2)} })). The parentheses around the object literal are required so the braces are read as an object rather than a function body. Each callback call builds a new object, so the source objects are not modified.
Exercise
const a = [5, 6]; const r = a.map((n, i, arr) => { arr.push(n); return n + 1; }); What are r and a afterwards?
Show answer
r is [6, 7] and a is [5, 6, 5, 6]. map reads the length (2) once before it starts, so the pushed elements are never visited, but they do remain in the source array.