Topic 47 of 87
Array map()
Overview
The .map() method creates a brand new array by executing a function on every element of the original array.
This is the most important array method to master if you plan on learning React. It is used constantly to transform raw data (like numbers or JSON objects) into a new format (like UI components or specific strings).
Syntax
Transforming Data
javascript
const numbers = [1, 2, 3, 4];
// Map creates a NEW array where every number is doubled
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
console.log(numbers); // [1, 2, 3, 4] (Original is untouched!)Extracting specific properties
javascript
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
// Extract just the names into a flat array of strings
const names = users.map(user => user.name);
console.log(names); // ["Alice", "Bob"]Common Pitfalls
- Forgetting to
returna value in the callback function. If you open curly braces{}in an arrow function, you must explicitly typereturn. If you forget,.map()will fill the new array entirely withundefined.
Interview Questions
Q:
What is the difference between
.forEach() and .map()?A:
.forEach() iterates over the array to perform side effects and returns undefined. .map() iterates over the array to transform data and returns a completely new array of the same length.
Real-World Example
Rendering a list of JSX components in React based on an array of data objects.
example
javascript
return (
<ul>
{users.map(u => <li key={u.id}>{u.name}</li>)}
</ul>
);Check Your Knowledge
Test your understanding of Array map() with these quick questions.