iteration

Array.prototype.map

Creates a new array populated with the results of calling a callback on every element of the calling array. Reach for it whenever you want to transform each element 1-to-1 into a new value.

arr.map(callbackFn[, thisArg])

Parameters

Parameter Purpose
callbackFn(element, index, array) Function whose return value becomes the new element
thisArg Value used as `this` inside callbackFn

Examples

console.log([1,2,3].map(n => n * 2));

Logs: [2, 4, 6]

console.log(['a','b','c'].map((v, i) => `${i}:${v}`));

Logs: ['0:a', '1:b', '2:c']

console.log([{n:'Ada'},{n:'Ben'}].map(u => u.n));

Logs: ['Ada', 'Ben']

console.log(['1','2','3'].map(Number));

Logs: [1, 2, 3]

Gotcha

map returns a new array; forEach returns undefined. Passing parseInt directly (`.map(parseInt)`) breaks because parseInt receives the index as radix — use `.map(Number)` or `.map(s => parseInt(s, 10))`.

Related methods

← All JS array methods · TypeScript vs JavaScript