Sub topic 4
map: Transforming Every Element
This chapter assumes you can write arrow functions, know what a callback is, and know that array methods can return new arrays instead of changing the original. Earlier chapters covered those ideas. Here we look at map itself: what it does, what it returns, and the mistakes people make with it most often.
The Working Model
map calls your callback once for each element, in index order. It takes whatever the callback returns and puts it in a new array at the same index. Three rules follow from this:
- The result always has the same length as the source array.
- The source array is not changed by
mapitself. - Each output element is exactly the callback's return value, so a callback with no
returnproducesundefined.
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)When to Reach for map
Use map when every input produces exactly one output. Typical cases include converting units, formatting values for display, pulling one field out of each object, and wrapping values in a new shape.
const products = [
{ sku: 'A1', name: 'Lamp', priceCents: 2499 },
{ sku: 'B2', name: 'Desk', priceCents: 15900 }
];
const skus = products.map(p => p.sku);
const labels = products.map(p => `${p.name}: $${(p.priceCents / 100).toFixed(2)}`);
const rows = products.map((p, i) => ({ row: i + 1, sku: p.sku }));
console.log(skus); // ['A1', 'B2']
console.log(labels); // ['Lamp: $24.99', 'Desk: $159.00']
console.log(rows); // [{ row: 1, sku: 'A1' }, { row: 2, sku: 'B2' }]If some inputs should produce no output, use filter instead, or combine it with map. If one input should produce several outputs, flatMap fits better. Later chapters cover both.
Common Errors
Forgetting to return
With a braced arrow body, you must write return yourself. If you leave it out, the callback returns undefined and the result fills with undefined.
const nums = [1, 2, 3];
const broken = nums.map(n => { n * 2; });
const fixed = nums.map(n => { return n * 2; });
console.log(broken); // [undefined, undefined, undefined]
console.log(fixed); // [2, 4, 6]Returning an object literal without parentheses
In n => { value: n }, JavaScript reads the braces as a function body, not an object. The value: part becomes a label. Wrap the literal in parentheses:
const wrapped = [1, 2].map(n => ({ value: n }));
console.log(wrapped); // [{ value: 1 }, { value: 2 }]Using map for side effects
If you only want to log or save each element and you discard the result, use forEach or a for...of loop. A map call whose result is never used still builds an array for nothing. It also tells the reader that a transformation is happening when none is.
Expecting map to change the original
map returns a new array, so you have to store or use that result. Writing arr.map(fn); on a line by itself leaves arr exactly as it was.
Quick Reference
| Question | Answer for `map` |
|---|---|
| Output length | Same as input |
| Output elements | Callback return values |
| Mutates source array | No |
| Callback with no `return` | Produces `undefined` |
| Better fit for side effects | `forEach` or `for...of` |
Exercise
What does [10, 20, 30].map((n, i) => { n + i; }) return, and how would you fix it so it returns [10, 21, 32]?
Show answer
It returns [undefined, undefined, undefined] because the braced body has no return. Fix it with [10, 20, 30].map((n, i) => n + i) or by adding return n + i; inside the braces.
Exercise
Given const users = [{ id: 7, email: '[email protected]' }, { id: 9, email: '[email protected]' }];, write one map call that produces [{ userId: 7 }, { userId: 9 }].
Show answer
users.map(u => ({ userId: u.id })). The parentheses around the object literal stop JavaScript from reading the braces as a function body.