Learn how .map() transforms every array element into a new array of identical length without mutating the source array.
Learn how variables act as labeled containers for data using const, let, and var to manage lexical scope and reassignment safely in modern applications.
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().Use .map() whenever you want to transform items 1-to-1. Next, let's learn how to filter arrays using .filter()!