JavaScript Array.map() Method - Transform Every Element

Learn how to use Array.map() to transform every element in an array. Includes syntax, examples with objects, and common React patterns. Free browser-based reference.

Iteration

Detailed Explanation

Understanding Array.map()

Array.map() is one of the most frequently used JavaScript array methods. It creates a new array by calling a provided function on every element of the original array. The original array is never modified.

Syntax

const newArray = array.map((element, index, array) => {
  // return transformed element
});

The callback receives three arguments:

  • element — the current element being processed
  • index — the index of the current element
  • array — the original array (rarely used)

Basic Examples

// Double every number
const nums = [1, 2, 3, 4];
const doubled = nums.map(n => n * 2);
// doubled: [2, 4, 6, 8]

// Extract a property from objects
const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 }
];
const names = users.map(user => user.name);
// names: ["Alice", "Bob"]

map() in React

In React, map() is the standard way to render lists of components:

const items = ["Apple", "Banana", "Cherry"];
return (
  <ul>
    {items.map((item, index) => (
      <li key={index}>{item}</li>
    ))}
  </ul>
);

map() vs forEach()

Both iterate over every element, but:

  • map() returns a new array of transformed values
  • forEach() returns undefined and is used only for side effects

If you do not need the resulting array, use forEach() instead.

Common Pitfalls

  1. Forgetting to return — arrow functions without braces auto-return, but with braces you must explicitly return
  2. Using map for side effects — if you do not need the result array, use forEach
  3. Sparse arraysmap() skips empty slots in sparse arrays

Use Case

Use map() whenever you need to transform data before displaying it -- converting API responses to UI-friendly formats, extracting specific fields from objects, or rendering React component lists from arrays of data.

Try It — JavaScript Array Methods Reference

Open full tool