Array.prototype.map
Creates a new array by transforming every element.
Available since: ES5
Syntax
array.map(callbackFn)Parameters
| Parameter | Type | Description |
|---|---|---|
| callbackFn | Function | A function that receives the element, its index and the whole array, and returns the new value. |
Return value
ArrayA new array of the same length holding the results of the function calls.
Examples
Doubling every number:
console.log([1, 2, 3].map((n) => n * 2).join(', '));Output:
2, 4, 6One property from each object:
const users = [{ name: 'Anna' }, { name: 'Oleg' }];
console.log(users.map((user) => user.name).join(', '));Output:
Anna, OlegNotes
The source array is not modified. If you do not need the result and only want to run an action for each element, use forEach().
See also
- Array.prototype.filter — Creates a new array from the elements that pass a test.
- Array.prototype.forEach — Runs a function for every element of an array.
- Array.prototype.flatMap — Maps each element with a function and flattens the result one level.
- Array.from — Creates an array from a string, Set, Map or another iterable.
Related recipes
In the tutorial
- map, filter and reduce — The three main array processing methods in JavaScript: transforming, selecting and reducing to a single value.