map
map builds a new array by running a function on every item, and it is the method you will use more than any other.
map returns a new array of the same length, holding whatever the callback returned each time. The original is untouched. Forgetting to return from the callback fills the new array with undefined.
EXERCISE
1One In, One Out
map gives you a new array with exactly as many items as the old one, each one transformed by your function.
The shape:
const numbers = [1, 2, 3];
const doubled = numbers.map((n) => n * 2);
console.log(doubled); // [ 2, 4, 6 ]
console.log(numbers); // [ 1, 2, 3 ] <- untouched
Three items in, three items out. Every time.
Compare with the loop it replaces:
const numbers = [1, 2, 3];
// The manual version:
const doubled = [];
for (const n of numbers) {
doubled.push(n * 2);
}
// The same thing, said once:
const doubled2 = numbers.map((n) => n * 2);
The loop version needs a let or an empty const array, a push, and three lines of scaffolding that are the same every time. map is that scaffolding, named.
Pulling one field out of a list of objects:
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Grace" },
{ id: 3, name: "Alan" },
];
const names = users.map((user) => user.name);
console.log(names); // [ 'Ada', 'Grace', 'Alan' ]
const ids = users.map((user) => user.id);
console.log(ids); // [ 1, 2, 3 ]
Reshaping each object:
const products = [
{ name: "Tea", price: 40 },
{ name: "Coffee", price: 120 },
];
const withTax = products.map((p) => ({
name: p.name,
price: p.price * 1.18,
}));
console.log(withTax[1].price); // 141.6
console.log(products[1].price); // 120 <- the original is safe
Note the round brackets around that object. Without them the braces read as a function body, which is the arrow trap from Unit 5.
Say "map to" when you read it and the meaning becomes obvious: map these users to their names, map these prices to prices with tax. The output always has the same number of items as the input, which is what separates map from filter in the next lesson.
EXERCISE
2The Callback Must Return Something
map collects whatever your callback hands back, so a callback that returns nothing gives you an array of undefined.
The bug, in the shape it always takes:
const numbers = [1, 2, 3];
const result = numbers.map((n) => {
n * 2; // calculated, and thrown away
});
console.log(result); // [ undefined, undefined, undefined ]
The braces made a function body, and a body with no return gives undefined. Three times.
Two correct versions:
// Implicit return, no braces:
const a = numbers.map((n) => n * 2);
console.log(a); // [ 2, 4, 6 ]
// Explicit return, with braces:
const b = numbers.map((n) => {
return n * 2;
});
console.log(b); // [ 2, 4, 6 ]
The same trap when returning an object:
const users = [{ name: "Ada" }];
const bad = users.map((u) => { name: u.name });
console.log(bad); // [ undefined ]
const good = users.map((u) => ({ name: u.name }));
console.log(good); // [ { name: 'Ada' } ]
map with an index:
const names = ["Ada", "Grace", "Alan"];
const numbered = names.map((name, i) => `${i + 1}. ${name}`);
console.log(numbered);
// [ '1. Ada', '2. Grace', '3. Alan' ]
And a reminder of what map is not for:
const names = ["Ada", "Grace"];
// Wrong tool: you want forEach, because nothing is being collected.
names.map((name) => console.log(name));
// It works, and it builds an array of undefined that you discard.
names.forEach((name) => console.log(name)); // say what you mean
Pro Tip: An array full of
undefinedafter amapmeans one thing every time: the callback has braces and noreturn. It is the single most commonmapbug, and recognising the symptom saves you from reading the logic looking for a fault that is not there.
EXERCISE
3Chaining and Practical Shapes
Because map returns an array, another array method can be called straight on the result, and that is how real transformations are written.
Chaining two methods:
const users = [
{ name: "Ada", age: 36 },
{ name: "Grace", age: 45 },
{ name: "Alan", age: 41 },
];
const namesOfOlder = users
.filter((user) => user.age > 40)
.map((user) => user.name);
console.log(namesOfOlder); // [ 'Grace', 'Alan' ]
filter is the next lesson. The point here is that .filter(...) gives back an array, so .map(...) can run on it immediately.
Order matters for both result and cost:
// Filter first, then map: map runs on 2 items.
users.filter((u) => u.age > 40).map((u) => u.name);
// Map first, then filter: map runs on all 3, and the filter
// can no longer see age, because map threw everything else away.
// users.map((u) => u.name).filter((name) => name.age > 40); // broken
map with join, for output:
const items = [
{ name: "Tea", qty: 2 },
{ name: "Coffee", qty: 1 },
];
const receipt = items
.map((item) => `${item.qty} x ${item.name}`)
.join("\n");
console.log(receipt);
// 2 x Tea
// 1 x Coffee
Converting types across a whole array:
const typed = ["10", "20", "30"];
const asNumbers = typed.map(Number);
console.log(asNumbers); // [ 10, 20, 30 ]
// Passing `Number` directly works because map calls it with each item.
// Be careful with this shortcut: parseInt takes a second argument,
// and map passes the index into it.
console.log(["10", "20", "30"].map(parseInt)); // [ 10, NaN, NaN ]
Pro Tip: Filter before you map whenever both are involved. It keeps the transformation working on the smallest set, and more importantly it keeps the full object available to the filter, because once
maphas reduced each item to a name there is nothing left to filter on.
