Sub topic 8
Transforming Every Element with map
This chapter assumes you know arrow functions, object literals and spread syntax, and the callback signature (element, index, array) covered in the previous chapter. It also assumes you can tell mutating methods from non-mutating ones. Here you will learn how map works, where it goes wrong, and when to pick a different tool.
What map does
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 original array is not changed.
const prices = [10, 25, 4];
const withTax = prices.map(price => price * 1.2);
console.log(withTax); // [12, 30, 4.8]
console.log(prices); // [10, 25, 4] (unchanged)Think of map as a one-to-one conversion. Each input slot produces exactly one output slot, in the same order. If you need fewer elements, use filter. If you need one combined value, use reduce. If one input should become several outputs, use flatMap, which a later chapter covers.
The callback signature in practice
map passes three arguments to your callback: the current element, its index, and the whole array. Most callbacks use only the first one, but the index is often handy.
const names = ['Ana', 'Ben', 'Cleo'];
const numbered = names.map((name, index) => `${index + 1}. ${name}`);
console.log(numbered); // ['1. Ana', '2. Ben', '3. Cleo']The third argument lets a callback look at neighbors without relying on an outer variable:
const readings = [3, 7, 4, 9];
const changes = readings.map((value, i, arr) => (i === 0 ? 0 : value - arr[i - 1]));
console.log(changes); // [0, 4, -3, 5]map also accepts an optional second argument, thisArg, which sets this inside a regular function callback. Arrow functions ignore it, because they take this from the code around them. In modern code you will rarely need thisArg.
Mapping arrays of objects
Real data usually arrives as an array of objects. map is the standard way to reshape it, for example to pick fields or derive new ones.
const users = [
{ id: 1, first: 'Ana', last: 'Silva', age: 31 },
{ id: 2, first: 'Ben', last: 'Okafor', age: 17 }
];
const ids = users.map(u => u.id);
const labels = users.map(u => ({ id: u.id, fullName: `${u.first} ${u.last}` }));
console.log(ids); // [1, 2]
console.log(labels); // [{ id: 1, fullName: 'Ana Silva' }, { id: 2, fullName: 'Ben Okafor' }]Notice the parentheses around the object literal in labels. Without them, JavaScript reads { as the start of a function body, not an object.
Common errors
Forgetting return in a block body
A concise arrow function (x => x * 2) returns its expression. As soon as you add braces, you must write return yourself. Leaving it out gives you an array full of 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]Mutating objects inside the callback
map returns a new array, but that array is a shallow result. If your callback changes the object it receives, it changes the original object, because both arrays hold references to the same objects.
const accounts = [{ name: 'Ana', active: false }];
const bad = accounts.map(acc => {
acc.active = true;
return acc;
});
console.log(accounts[0].active); // true (original changed!)
console.log(bad[0] === accounts[0]); // true (same object)
const accounts2 = [{ name: 'Ben', active: false }];
const good = accounts2.map(acc => ({ ...acc, active: true }));
console.log(accounts2[0].active); // false
console.log(good[0].active); // trueSpread creates a new top-level object. Nested objects inside it are still shared. If you need to change a nested property, spread that level too: ({ ...acc, address: { ...acc.address, city: 'Lisbon' } }).
Passing a function that takes extra arguments
Passing a named function straight to map is tidy, but map always sends three arguments. If that function treats its second parameter as something other than an index, you get surprising results. The classic case is parseInt, whose second parameter is the radix (number base).
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 base 1 is invalid. parseInt('3', 2) returns NaN because 3 is not a binary digit. Number ignores extra arguments, so it is safe to pass directly. When you are unsure what a function does with extra arguments, wrap it in an arrow function.
Using map only for side effects
If you call map and throw away the result, you build an array for nothing and mislead whoever reads your code. Use forEach or for...of for side effects such as logging or sending requests.
const items = ['a', 'b'];
items.map(item => console.log(item)); // works, but wasteful and misleading
items.forEach(item => console.log(item)); // states the intent clearlyEdge cases
Sparse arrays
map skips holes in sparse arrays. It does not call the callback for a missing index, and the hole stays a hole in the result. An explicit undefined value is different: it is a real element, and the callback runs for it.
const sparse = [1, , 3];
const dense = [1, undefined, 3];
console.log(sparse.map(x => x * 2)); // [2, <1 empty item>, 6] in Node; [2, empty, 6] in browsers
console.log(dense.map(x => x * 2)); // [2, NaN, 6]Changing the array during map
map fixes the range of indexes before it starts. Elements you push during the call are not visited. Elements you change before map reaches them are seen with their new values. Avoid both situations, because readers will not expect them.
Async callbacks
An async callback returns a promise, so map gives you an array of promises, not results. Combine them with Promise.all:
const fetchDouble = async n => n * 2;
async function main() {
const promises = [1, 2, 3].map(fetchDouble);
console.log(promises.length); // 3 (Promise objects)
const results = await Promise.all(promises);
console.log(results); // [2, 4, 6]
}
main();Choosing between map and its neighbors
| Goal | Tool | Returns |
|---|---|---|
| Convert each element to one new value | `map` | New array, same length |
| Run a side effect for each element | `forEach` or `for...of` | `undefined` |
| Keep only some elements | `filter` | New array, same or shorter |
| Collapse elements into one value | `reduce` | Any single value |
| Turn each element into zero or more values | `flatMap` | New flattened array |
| Stop early when a condition is met | `for...of` with `break`, or `find` | Depends |
map cannot stop early. It always visits every present element. If you need to stop partway through, use a loop or a search method.
Exercises
Exercise
Given const products = [{ name: 'Pen', cents: 150 }, { name: 'Ink', cents: 899 }];, write one map call that returns ['Pen: $1.50', 'Ink: $8.99'] without changing products.
Show answer
products.map(p => ${p.name}: $${(p.cents / 100).toFixed(2)}). The callback builds a new string from each object and never assigns to p, so products stays unchanged.
Exercise
Why does ['10', '10', '10'].map(parseInt) return [10, NaN, 2]?
Show answer
map calls parseInt(element, index, array), so the index becomes the radix. parseInt('10', 0) treats 0 as "use the default", giving 10. parseInt('10', 1) uses the invalid base 1, giving NaN. parseInt('10', 2) reads binary 10, giving 2. Use s => parseInt(s, 10) or Number instead.
Exercise
A teammate writes const flagged = orders.map(o => { o.flag = o.total > 100; return o; });. What is wrong, and how would you fix it?
Show answer
The callback mutates each original order object, so orders changes too, and flagged holds the same objects as orders. Return a new object instead: orders.map(o => ({ ...o, flag: o.total > 100 })).