Transforming Arrays with .map()
Quick Overview
`.map()` returns a new array of exactly the same length, one output per input. That length guarantee is the whole difference from `.filter()`, and why a map that drops items is the wrong tool.
Deep Dive
1. Pure Array Transformations
The .map() method creates a new array populated with the results of calling a provided callback function on every element in the calling array.
2. Why It Matters
.map() is non-mutating (pure). It leaves the original array untouched and returns a brand new transformed array of identical length. It powers UI rendering in frameworks like React (items.map(item => <ItemCard />)).
3. The Pattern
Pass a callback function to .map() that receives (item, index, array) and returns the transformed item:
const prices = [10, 20, 30];
// Double every price
const doubledPrices = prices.map((price) => price * 2);
console.log(doubledPrices); // [20, 40, 60]
console.log(prices); // [10, 20, 30] (Original array untouched!)
4. Transforming Objects in Arrays
.map() is frequently used to extract or reformat properties from array object lists:
const users = [
{ id: 1, name: "Alex" },
{ id: 2, name: "Sarah" },
];
// Extract just names into a string array
const names = users.map((user) => user.name);
console.log(names); // ["Alex", "Sarah"]
5. Common Mistakes
- Forgetting to Return Inside Callback: If your callback function inside
.map()does not explicitly return a value (or use an implicit 1-line arrow return), the new array will be filled withundefined! - Using .map() When You Don't Want a Return Array: If you are not using the returned array and just want to iterate with side effects, use
.forEach(), not.map().
6. Try It Yourself
Write it yourself. The tests below run against your code.
Double Prices with .map()
Examples
7. Next Steps
Use .map() whenever you want to transform items 1-to-1. Next, let's learn how to filter arrays using .filter()!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.