Array.prototype.map()
One in, one out — the result always has the same length as the input. If you are dropping elements you want filter; if you are returning nothing you want forEach.
Demo
Every element goes through the callback and the results form a new array of exactly the same length — three in, three out, always. The empty case returns an empty array rather than an error. Note that the original array is untouched: map is one of the non-mutating Array methods, which is the dividing line that causes most Array confusion.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| callback | Function | yes | Called as callback(element, index, array) for every element. Its return value becomes the corresponding element of the new array. |
| thisArg | any | no (undefined) | Value of `this` inside the callback. Ignored for arrow functions, which take `this` from the enclosing scope. |
Return value
Array — A NEW array of the same length, holding whatever the callback returned for each element. The original array is never modified.
Common patterns
const names = users.map(u => u.name);
const nums = ['1', '2', '3'].map(Number);
const numbered = items.map((x, i) => `${i + 1}. ${x}`);
Examples
Pitfalls
[1, 2].map(x => { x * 2 })
[1, 2].map(x => x * 2)
['1', '2', '3'].map(parseInt)
['1', '2', '3'].map(x => parseInt(x, 10))
items.map(x => console.log(x));
items.forEach(x => console.log(x));
[1, 2, 3].map(x => x > 1 ? x : undefined)
[1, 2, 3].filter(x => x > 1)
When to use
- Transforming every element into something else
- Extracting one field from an array of objects
- Converting types across a whole array
- Anywhere a for loop would just push into a result array
- You need fewer elements out than in → filter
- The callback returns nothing → forEach
- You are reducing to a single value → reduce
- You need to stop early → a for...of loop with break
Notes
FAQ
Because map calls the callback with (element, index, array) and parseInt takes (string, radix). The index arrives as the radix: index 0 means "auto", index 1 is an invalid radix giving NaN, index 2 parses in binary. Wrap the call so only the element is passed.
['1', '2', '3'].map(x => parseInt(x, 10)) // [1, 2, 3]