Sub topic 8
Transforming Every Element with map
This chapter assumes you know arrow functions, object property access, and the (element, index, array) callback signature from the previous chapter. It also assumes you know the difference between mutating and non-mutating methods.
The working model
map calls your callback once for each element. It collects whatever the callback returns into a new array. The result always has the same length as the original, and the original array is left unchanged.
const prices = [10, 20, 30];
const withTax = prices.map(price => price * 1.2);
console.log(withTax); // [12, 24, 36]
console.log(prices); // [10, 20, 30]Use map when you need one output value for every input value. Common uses are converting units, pulling out a single property, or reshaping objects.
const users = [
{ id: 1, first: 'Ana', last: 'Silva' },
{ id: 2, first: 'Ben', last: 'Okafor' }
];
const names = users.map(u => u.first);
console.log(names); // ['Ana', 'Ben']
const labels = users.map((u, i) => `${i + 1}. ${u.first} ${u.last}`);
console.log(labels); // ['1. Ana Silva', '2. Ben Okafor']Common errors
Forgetting `return` in a block body
An arrow function with curly braces needs an explicit return. Without it, every element becomes undefined.
const nums = [1, 2, 3];
const wrong = nums.map(n => { n * 2; });
console.log(wrong); // [undefined, undefined, undefined]
const right = nums.map(n => { return n * 2; });
console.log(right); // [2, 4, 6]Returning an object literal
JavaScript reads n => { value: n } as a block containing a label, so the callback returns nothing. Wrap the object in parentheses.
const ids = [1, 2];
console.log(ids.map(id => ({ id, active: true })));
// [{ id: 1, active: true }, { id: 2, active: true }]Passing a function that takes extra parameters
map passes three arguments: the element, the index, and the array. A function with an optional second parameter will receive the index in that slot, and the results can be wrong.
console.log(['1', '2', '3'].map(parseInt)); // [1, NaN, NaN]
console.log(['1', '2', '3'].map(s => parseInt(s, 10))); // [1, 2, 3]
console.log(['1', '2', '3'].map(Number)); // [1, 2, 3]parseInt('2', 1) returns NaN because 1 is not a valid radix.
Mutating objects inside the callback
map returns a new array, but the objects in it are the same objects unless you create new ones. If you change a property on the element inside the callback, you change the original.
const items = [{ qty: 1 }, { qty: 2 }];
const doubled = items.map(item => ({ ...item, qty: item.qty * 2 }));
console.log(doubled); // [{ qty: 2 }, { qty: 4 }]
console.log(items); // [{ qty: 1 }, { qty: 2 }]When map is the wrong tool
| Goal | Better choice |
|---|---|
| Keep only some elements | `filter` |
| Produce one total value | `reduce` |
| Map to arrays and flatten them | `flatMap` |
| Run a side effect per element | `forEach` / `for...of` |
Exercise
What does [1, 2, 3].map(n => { n + 1 }) return, and how would you fix it so it returns [2, 3, 4]?
Show answer
It returns [undefined, undefined, undefined] because the block body has no return statement. Fix it with n => n + 1 or n => { return n + 1; }.
Exercise
Given const products = [{ name: 'pen', cents: 150 }, { name: 'pad', cents: 325 }], write a map call that returns [{ name: 'pen', dollars: 1.5 }, { name: 'pad', dollars: 3.25 }] without changing products.
Show answer
products.map(p => ({ name: p.name, dollars: p.cents / 100 })). The parentheses around the object literal make the arrow function return the object, and building a new object leaves the originals untouched.