Map
An array method that creates a new array by calling a provided function on every element in the calling array, transforming each element.
Overview
The map() method is one of the most commonly used array methods in JavaScript. It creates a new array with the results of calling a provided function on every element in the array. Unlike forEach(), map() returns a new array and doesn't modify the original array, making it ideal for functional programming.
Example
javascript// Basic transformation const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10] // Transform objects const users = [ { name: 'Alice', age: 30 }, { name: 'Bob', age: 25 } ]; const names = users.map(user => user.name); // ['Alice', 'Bob'] // With index const indexed = ['a', 'b', 'c'].map((item, index) => ({ id: index, value: item })); // [{id: 0, value: 'a'}, {id: 1, value: 'b'}, {id: 2, value: 'c'}]
Key Points
- Returns a new array
- Doesn't modify the original array
- Callback receives: element, index, array
- Perfect for transforming data
- Commonly used in React for rendering lists
Learn More
- Array - JavaScript arrays
- Callback - Callback functions
- Arrow Function - Arrow functions
- MDN: Array.map()