Skip to Content
Built Ins.map()

.map()

Array method that transforms every element and returns a new array of the same length. The original array is never modified.

When to use it

  • Transforming data — converting an array of objects into a different shape
  • Extracting fields — pulling one property out of each item
  • Rendering lists — turning data into JSX or HTML strings
  • Chaining — combine with .filter() or .sort() in a pipeline

Anatomy

const result = array.map((element, index, array) => { // element — the current item // index — its position (0-based) // array — the original array (rarely used) return newValue // whatever you return becomes the new element })

At a glance

ParameterWhat it is
elementCurrent item being processed
indexPosition in the array (0-based)
arrayThe original array (rarely needed)
Return valueNew array with the returned values

1. Simple — transform values

const nums = [1, 2, 3] const doubled = nums.map(n => n * 2) doubled // [2, 4, 6] nums // [1, 2, 3] — untouched

2. Intermediate — extract and reshape

const users = [ { id: 1, name: 'Alice', email: 'alice@test.com' }, { id: 2, name: 'Bob', email: 'bob@test.com' }, ] // extract just the names const names = users.map(u => u.name) // ['Alice', 'Bob'] // reshape into a different structure const options = users.map(u => ({ value: u.id, label: `${u.name} (${u.email})`, })) // [{ value: 1, label: 'Alice (alice@test.com)' }, ...]

3. Advanced — chain with filter

const products = [ { name: 'Shirt', price: 25, inStock: true }, { name: 'Pants', price: 40, inStock: false }, { name: 'Hat', price: 15, inStock: true }, ] const available = products .filter(p => p.inStock) // keep only in-stock items .map(p => `${p.name} — $${p.price}`) // format as display strings // ['Shirt — $25', 'Hat — $15']

Filter first, then map. This avoids transforming items you’re about to discard.


Gotchas

Forgetting to return

const nums = [1, 2, 3] // arrow with braces needs an explicit return nums.map(n => { n * 2 }) // [undefined, undefined, undefined] nums.map(n => { return n * 2 }) // [2, 4, 6] nums.map(n => n * 2) // [2, 4, 6] — implicit return (no braces)

Don’t use map for side effects

// map returns a new array — if you're ignoring the result, use forEach users.map(u => console.log(u.name)) // works but wasteful — builds an unused array users.forEach(u => console.log(u.name)) // correct — no array created

  • .filter() — keep elements that match, often chained before .map()
  • .forEach() — loop without building a new array
  • .reduce() — when .map() isn’t enough and you need to accumulate
  • Array — the full list of array methods
Last updated on