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.
The .map() method creates a new array populated with the results of calling a provided callback function on every element in the calling array.
.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 />)).
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!)
.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"]
.map() does not explicitly return a value (or use an implicit 1-line arrow return), the new array will be filled with undefined!.forEach(), not .map().Write it yourself. The tests below run against your code.
Use .map() whenever you want to transform items 1-to-1. Next, let's learn how to filter arrays using .filter()!
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.
`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.
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.
Average 5.0 by 1 learner